如何使用MVVM在双击列表框项上触发命令? [英] How to fire a command on double-click listbox item using MVVM?

查看:86
本文介绍了如何使用MVVM在双击列表框项上触发命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户双击列表框项时,我正在尝试启动ICommand。另外,我正在尝试使用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.

在此XAML中,按键 p可完美工作。当我双击列表框时,该命令永远不会启动。我设置了一个断点,以确认双击时不会调用 PlayVideoCommand。我是否缺少某些东西,还是必须使用我不熟悉的Setter?

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>

双击和 p都应执行相同的命令。使用鼠标时,我可以看到已选择listboxitem。我有一种预感,即MouseBinding Command属性不是依赖项属性,但我不知道如何确认。

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.

推荐答案

您的示例中发生的是,列表框本身对双击有反应,但仅在列表框项未覆盖的部分区域内。

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.

您需要将事件处理程序绑定到listboxitem。

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

此处有一些方法:
双击ListBox项以打开浏览器

关于为什么在MVVM中进行少量代码隐藏并不一定是一件可怕的事情的一些讨论:
使用MVVM从WPF ListView项中引发双击事件

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

更多讨论:
http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/9fb566a2-0bd6-48a7-8db3-312cd3e93340/

这篇关于如何使用MVVM在双击列表框项上触发命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆