If you are building out a WP7 (or just a standard Silverlight application) and you are following the MVVM design pattern you may be a left wondering how to handle the selectionChanged event in a Listbox without the use of a code behind. For this post we are using the MVVMLight framework to accomplish our goals, but this same concept should hold true in all general cases.
Step 0 – Setting up your system
In order to get this up and running you will need to have downloaded and referenced the MVVMlight framework in your application. You will want to reference:
GalaSoft.MvvmLight.Extras.WP7
GalaSoft.MvvmLight.WP7
Step 1 – Creating your references in your .Xaml file
The image below will show you how to setup your references in your .xaml file to have the right aliases
Step 2 – Defining your Triggers in XAML
In order to NOT have to use the code behind we need to use the interactivity triggers which are available to use in Xaml. What you want to pay attention to here is the Eventname. This needs to be SelectionChanged. For the EventToCommand make sure you provide the name of the ICommand property in your ViewModel (we will create this in a minute). Also make sure to set the PassEventArgsToCommand to True.
Step 3 – Defining your ICommand in your ViewModel
First lets create our property which is our ICommand (here it is implemented as a RelayCommand class)
public RelayCommand PatientTaskSelectedCommand { get; set; }
Next we want to create the pointer for our Comman
PatientTaskSelectedCommand = new RelayCommand( HandlePatientTaskSelected );
Finally our method HandlePatientTaskSelected method which does the heavy lifting
private void HandlePatientTaskSelected( SelectionChangedEventArgs args )
{
if ( args == null || args.AddedItems.Count == 0 ) { return; }
if ( args.AddedItems[0] as Task == null )
{ throw new InvalidCastException("The model type provided for Patient Task was not a Task, this is not correct.");}
var task = args.AddedItems[0] as Task;
RaiseNavigateToPage( RouteCreator.ToPatientTaskDetails( task.Id ) );
}
That is all, as you can see there is a bit of work which needs to be done, but not a tone.
Till next time,
Posted
08-05-2010 5:07 PM
by
Derik Whittaker