Passing Parameters With Behaviors In MVVM Light for Windows Phone

Windows Phone From Scratch #20
MVVM Light Toolkit Soup To Nuts #5

In the previous posting in this series, we created a list of customers and we bound mvvm navigation them to a list box. We did this not in the code-behind but in the View-Model. This forces the question of how we respond when a user makes a selection in the list box, if the logic for handling the selection is to be not in the view (the code-behind) but in the view-model.

The answer will not be overly surprising to anyone who has been following this series; we’ll use a behavior to capture the selected value and pass the selection to the view model class.  The trick here is to use RelayCommand<T> rather than a simple RelayCommand.

Taking this step by step, please re-open the project and create a new MVVMLight View named Details.  Also add a new MVVMLight View-Model named DetailsViewModel.  Wire them together as explained in Part 1.

Now, taking the lesson from Part 2, open MainViewModel.cs and add a property for the command (this will be bound to by the behavior)

public RelayCommand<Customer> DetailsPageCommand
{
   get;
   private set;
}

 

Note the type, which is RelayCommand<Customer> indicating that this command will take a parameter of type Customer (hint: it will be the selected item in the list box).

In the constructor initialize the RelayCommand:

DetailsPageCommand = new RelayCommand<Customer>(
    ( msg ) => GoToDetailsPage( msg ) );

 

Note here that msg is the Customer being passed as a parameter from the behavior to the implementing method.

Finally, implement the GoToDetailsPage method, passing along the parameter. Normally, this method would be responsible for actually navigating to the Details page and showing the customer details, but to simplify, we can have it just display a message box with the information received,

private object GoToDetailsPage( Customer msg )
{
   System.Windows.MessageBox.Show( 
         "Go to details page with: " + 
         msg.First + 
         " " + 
         msg.Last );
   return null;
}

 

Complete source is available here.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Mini-Tutorial, Patterns & Skills, Tools and Utilities, WindowsPhone and tagged , . Bookmark the permalink.