0
votes

I've data bound a ListBox in my MVVM Light Windows Phone 7 app, and want to invoke a command in my view model when the user clicks on an item in my ListBox.

I'm doing this using the EventToCommand behaviour and everything is good, except that I can't pass the data item associated with the list element that was clicked, if I use the MouseLeftButtonDown event ...

If I use the SelectionChanged event, then I can bind the behaviour's CommandParameter to the ListBox's SelectedItem, but I really want to use the MouseLeftButtonDown event.

Any ideas? I'd prefer not to pollute my View Model by setting the "PassEventArgsToCommand" option, and in any event I'm not sure I can get the selected data item from the MouseButtonEventArgs.

Right now I'm heading towards setting up an event handler in the code-behind, and invoking the ViewModel from there, using the "sender" to get at the data item.

Thanks,

Damian
2

2 Answers

0
votes

It looks like the question doesn't actually make sense - the MouseLeftButtonDown event being fired on the ListBox is not associated with a particular item in the ListBox.

Instead, I'm looking to hook up to this event on the ItemTemplate I've associated with the ListBox.

0
votes

Jesse Liberty gives a good example here: Passing Parameters...

But if you're using Windows Phone 7.5 you have to change one thing, which is you cannot use the Galasoft EventToCommand syntax anymore, as shown here in this example:

<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
    <!--<GalaSoft_MvvmLight_Command:EventToCommand x:Name="SelectionCommand" Command="{Binding SwitchProfileCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=lboxProfiles}"/>-->

    <i:InvokeCommandAction Command="{Binding SwitchProfileCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=lboxProfiles}" />

</i:EventTrigger>

Also, for Windows Phone 7.5, check out http://windowsphonegeek.com/articles/ListBox-ContextMenu-with-MVVM-in-Windows-Phone for using a command with a context menu linked to each item.