如何在MVVM模式下双击列表框项目时触发命令?

10

我正在尝试在用户双击列表框项目时启动ICommand。同时,我正在尝试使用MVVM模式来实现这一点。

在这个XAML中,按键“p”完美地工作。当我双击列表框时,命令从未启动。我设置了一个断点以确认“PlayVideoCommand”没有被双击调用。我是否漏掉了什么,或者我必须使用Setter(我不熟悉它)?

<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"键应该执行相同的命令。当使用鼠标时,我可以看到列表框项目被选中。我有一种预感,MouseBinding Command属性不是一个依赖属性,但我不知道如何确认。

3个回答

13
您的示例中发生的情况是,列表框本身对双击做出了响应,但仅在它的区域中没有被列表框项覆盖的部分。您需要将事件处理程序绑定到列表框项。
有几种方法可以实现这一点: 双击 ListBox 项以打开浏览器 一些关于为什么在 MVVM 中使用少量代码后台不一定是可怕的讨论: 使用 MVVM 从 WPF ListView 项触发双击事件 更多讨论: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9fb566a2-0bd6-48a7-8db3-312cd3e93340/

我看了你发的第二个链接,但希望自那几年前发布以来情况有所改变。我想我会在代码后台文件中添加几行代码。这个问题上我很难坚持使用MVVM。感谢你提供的详细信息。 - James

1

0
有人可能会争论代码后台是好是坏,但是可以使用一个命令。在ItemTemplate中添加LeftDoubleClick手势,像这样:
<UserControl.Resources>
    <DataTemplate x:Key="BrowseTemplate" >
        <StackPanel >
            <StackPanel.InputBindings>
                <MouseBinding Gesture="LeftDoubleClick"
                              Command="{Binding DataContext.PlayVideoCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Mode=OneWay}" 
                              CommandParameter="{Binding }" />
            </StackPanel.InputBindings>
            <TextBlock Text="{Binding }" Width="50" />
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接