Binding an MVVM Command to a listbox item


If you are trying to bind a Command to a listbox item that is on a View bound to a ViewModel, you may have been banging your heard trying to work out why the Command wasn’t firing ( I was anyway! ). The problem is that Silverlight is trying to find the Command in the context of the control within which it is bound. So in my instance, it was trying to find the Command within the ItemSource of the listbox, rather than looking in the ViewModel which is where definition for my Command exists.

Fortunately, I’m using the MVVM Light Toolkitframework  for my MVVM implentation in my Windows Phone 7 app. This has a really simple feature where you can find the ViewModel through a ViewModelLocator, so the binding on my EventToCommand becomes:

<GalaSoft_MvvmLight_Command:EventToCommand
Command="{Binding Source={StaticResource Locator}, Path=Main.DeleteCommand, Mode=OneWay}"/>

where Main is the name of my ViewModel. Simple!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s