Blog

Using the DelegateCommand to handle events in MVVM in Silverlight

Posted by Mike Gold Blogs | Learn .NET Mar 01, 2010
PRISM provides a mechanism for bringing event handling directly into your view model called the DelegateCommand. The delegate command can be used with XAML buttons to pass your data context into your view model upon clicking the button by the user
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.
COMMENT USING
PREMIUM SPONSORS
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.