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

馋奶兔 提交于 2019-12-23 07:47:44

问题


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.


回答1:


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/




回答2:


It seems that the ListBox doesn't handle double click on a ListBoxItem. This is a good answer: Can't bind Command to ListBox



来源:https://stackoverflow.com/questions/11172443/how-to-fire-a-command-on-double-click-listbox-item-using-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!