【问题标题】:Using ICommand and InputBindings consistently in DataGrid在 DataGrid 中一致地使用 ICommand 和 InputBindings
【发布时间】:2011-12-20 12:41:12
【问题描述】:

我正在尝试创建一个具有以下功能的 DataGrid:

  • 只读数据网格,但通过双击和单独的编辑表单提供编辑功能(双击特定行)
  • ContextMenu 调用新建/编辑/删除表单(右键单击整个 DataGrid)
  • 调用删除表单的删除键(在特定选定行上)

我认为使用 ICommand 是个好主意,所以我创建了一个这样的 DataGrid:

public class MyDataGrid : DataGrid {
    public static readonly RoutedCommand NewEntry = new RoutedCommand();
    public static readonly RoutedCommand EditEntry = new RoutedCommand();
    public static readonly RoutedCommand DeleteEntry = new RoutedCommand();

    public MyDataGrid() {
        CommandBindings.Add(new CommandBinding(NewEntry, ..., ...));
        CommandBindings.Add(new CommandBinding(EditEntry, ..., ...));
        CommandBindings.Add(new CommandBinding(DeleteEntry, ..., ...));

        InputBindings.Add(new InputBinding(DeleteCommand, new KeyGesture(Key.Delete)));
        InputBindings.Add(new MouseBinding(EditEntry, new MouseGesture(MouseAction.LeftDoubleClick)));

        // ContextMenu..working fine
    }
}

然后我意识到,双击一行是行不通的,所以我添加了这个:

LoadingRow += (s, e) =>
    e.Row.InputBindings.Add(new MouseBinding(EditEntry,
        new MouseGesture(MouseAction.LeftDoubleClick)));

当然删除键也不起作用,我添加了这个:

PreviewKeyDown += (s, e) => { if(e.Key == Key.Delete) { ... } };

为什么我必须这样做?使用命令来防止这种对事件的攻击难道不是重点吗?我错过了什么吗?

在我简单而完美的世界中,我想在 CanExecute 方法中决定是否适合处理命令,而不是订阅大量不同的事件处理程序..

【问题讨论】:

    标签: c# wpf wpfdatagrid routed-events icommand


    【解决方案1】:

    通常我使用Style将命令附加到DataGridCell

    这是一个使用自定义 AttachedCommandBehavior 的示例

    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="my:CommandBehavior.Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyView}}, Path=DataContext.ShowPopupCommand}" />
        <Setter Property="my:CommandBehavior.CommandParameter" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=DataContext}" />
        <Setter Property="my:CommandBehavior.Event" Value="MouseDoubleClick" />
    </Style>
    

    我不记得为什么我将它附加到单元而不是行,但我确信这是有原因的。您可以尝试将事件附加到 Row 中,看看会发生什么。

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2017-06-10
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2015-05-07
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多