Using the DelegateCommand to handle events in MVVM in Silverlight

Sometimes we want the View Model to handle the result of a button click, so we can manipulate data passed in by the user's click.  We can use the DelegateCommand PRISM structure to do this.  Unlike event handlers in XAML, a delegate command is an object utilizing the command pattern


The XAML looks like the line below.  We can bind the DelegateCommand of our ViewModel called EditCommand directly to the view.  We can also pass a parameter (the current data context of the view)



<Button Style="{StaticResource ItemEdit}" Content="VIEW/EDIT" cmd:Click.Command ="{Binding EditCommand}" cmd:Click.CommandParameter ="{Binding}" />

The view model would have the following code where IEditView represents the data context passed in by the button:


private DelegateCommand<IEditViewModel> editCommand = new DelegateCommand<IEditViewModel>(OnEditCommand);

public DelegateCommand<IEditViewModel> EditCommand
{
get { return editCommand ; }
set { editCommand = value; }
}
private static void OnEditCommand(IEditViewModel obj)
{

}

I wouldn't always recommend using the DelegateCommand in developing Silverlight apps.  If the button causes any direct results on the view itself, then you probably want to go back to the old event handler in the code behind.  The reason for this is that you want to keep all knowledge of the view out of the view model.  You can always delegate event handling from the code behind by assigning the DataContext to your view model and calling the viewmodel from the event handler.
Ebook Download
View all
Learn
View all