Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire a command on double-click listbox item using MVVM?

I'm trying to launch an ICommand when the user double-clicks on a listbox item. Also, I'm trying to do this using the MVVM pattern.

In this XAML, the key press "p" works perfectly. When I double click on the list box, the command never starts. I've set a break point to confirm "PlayVideoCommand" is not called with a double-click. Am I missing something or do I have to use Setter (which I'm not familiar with)?

<ListBox Name="SmallVideoPreviews" Grid.Column="1" MaxHeight="965"
    ItemsSource="{Binding BrowseVideos}" 
    ItemTemplate="{StaticResource BrowseTemplate}">
    <ListBox.InputBindings>
        <KeyBinding Key="p" 
            Command="{Binding PlayVideoCommand}"
            CommandParameter="{Binding ElementName=SmallVideoPreviews, Path=SelectedItem}"/>
        <MouseBinding Gesture="LeftDoubleClick"
            Command="{Binding PlayVideoCommand}"
            CommandParameter="{Binding ElementName=SmallVideoPreviews, Path=SelectedItem}"/>
    </ListBox.InputBindings>
</ListBox>

Both double-click and "p" should execute the same command. When using the mouse, I can see the listboxitem is selected. I have a hunch that the MouseBinding Command property is not a dependency property but I don't know how to confirm this.

like image 652
James Avatar asked Jun 23 '12 19:06

James


1 Answers

What's happening in your sample is that the listbox itself is reacting to the double click, but only in the part of it's area that is not covered by a list box item.

You need the event handler to be tied to the listboxitem.

Some ways to do it are here: Double Click a ListBox item to open a browser

And some discussion about why a little code-behind in MVVM is not necessarily a terrible thing: Firing a double click event from a WPF ListView item using MVVM

More discussion: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9fb566a2-0bd6-48a7-8db3-312cd3e93340/

like image 50
Japple Avatar answered Sep 24 '22 06:09

Japple