如何绑定命令双击DataGrid中的一行 [英] How to bind a Command to double-click on a row in DataGrid

查看:164
本文介绍了如何绑定命令双击DataGrid中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个WPF UserControl,用于选择列表如下:

I have developed a WPF UserControl that is intended to be used as a pick list as follows:


  • 绑定到CollectionView的DataGrid的实体(例如Employees)

  • DataGrid上方的TextBox可用于过滤DataGrid中显示的项目。

我想公开一个当用户双击DataGrid中的一行时将执行的命令。然后,容器可以通过在DataGrid中的SelectedItem进行某些操作来做出反应。

I want to expose a Command that will be executed when the user double-clicks on a row in the DataGrid. The container can then react to this by doing something with the SelectedItem in the DataGrid.

到目前为止,我已经尝试处理双击,如下所示:

So far I've tried to handle the double-click as follows:

<DataGrid IsReadOnly="True">
    <DataGrid.InputBindings>
        <MouseBinding MouseAction="LeftDoubleClick" Command="... />
    </DataGrid.InputBindings>
...

但是,当用户单击DataGrid标题时,双击事件仍然会触发,我想要限制它,以便命令是只有当双击属于DataGrid的主体时才执行,是否有声明的方式来执行此操作?

However the double-click event still fires when the user clicks in the DataGrid header. I'd like to be able to limit it so that the Command is only executed when the double click is in the body of the DataGrid. Is there a declarative way to do this?

更新

我只是掌握了WPF和MVVM,真正寻找如何实现这样的低级可重用组件的指导,还会感谢任何一般建议, upvoted。现在,我假设我会想要这个UserControl:

I'm just getting to grips with WPF and MVVM, and am really looking for guidance on how to implement low-level reusable components like this. Any general advice will also be gratefully received and upvoted. As it stands, I'm assuming I will want this UserControl to:


  • 公开一个依赖属性SelectedItem,绑定到DataGrid的SelectedItem

  • Expose a dependency property "SelectedItem" that is bound to the DataGrid's SelectedItem

显示当用户双击一行时触发的RoutedEventItemDoubleClick或类似信息。

Expose a RoutedEvent "ItemDoubleClick" or similar that is fired when the user double-clicks on a row.

实现 ICommandSource 并调用 CommandHelpers.ExecuteCommandSource(this)行双击事件处理程序。

Implement ICommandSource and call CommandHelpers.ExecuteCommandSource(this) from the row double-click event handler.

推荐答案

问题:

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <EventSetter Event="Loaded" Handler="Row_Loaded"/>
    </Style>
</DataGrid.RowStyle>





private void Row_Loaded(object sender, RoutedEventArgs e)
{
    var row = sender as DataGridRow;
    row.InputBindings.Add(new MouseBinding(MyCommands.MyCommand,
            new MouseGesture() { MouseAction = MouseAction.LeftDoubleClick }));
}

这篇关于如何绑定命令双击DataGrid中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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