Using the DelegateCommand to handle events in MVVM in Silverlight

By Mike Gold 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.
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE ... Read more