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

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

问题描述

我开发了一个 WPF UserControl,旨在用作选择列表,如下所示:

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

  • 绑定到实体(例如员工)的 CollectionView 的 DataGrid
  • 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,我真的在寻找有关如何实现像这样的低级可重用组件的指导.任何一般性建议也将被感激地接受和投票.就目前而言,我假设我希望这个 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:

  • 公开绑定到 DataGrid 的 SelectedItem 的依赖属性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.

推荐答案

如果代码后面没有问题:

If code behind is not a problem:

<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天全站免登陆