9

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

  • 绑定到实体集合视图(例如员工)的 DataGrid
  • DataGrid 上方的一个 TextBox,可用于过滤 DataGrid 中显示的项目。

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

到目前为止,我已尝试按如下方式处理双击:

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

但是,当用户单击 DataGrid 标头时,仍会触发双击事件。我希望能够限制它,以便仅在双击 DataGrid 的主体时执行命令。有没有一种声明性的方式来做到这一点?

更新

我刚刚开始掌握 WPF 和 MVVM,并且真的在寻找有关如何实现这样的低级可重用组件的指导。任何一般性的建议也将被感激地接受和赞成。就目前而言,我假设我希望这个 UserControl :

  • 公开绑定到 DataGrid 的 SelectedItem 的依赖属性“SelectedItem”

  • 公开当用户双击一行时触发的 RoutedEvent "ItemDoubleClick" 或类似事件。

  • 实现ICommandSourceCommandHelpers.ExecuteCommandSource(this)从行中调用双击事件处理程序。

4

2 回答 2

10

如果后面的代码不是问题:

<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 }));
}
于 2011-04-27T18:22:51.693 回答
1

您可以简单地将 DataGrid 放入 Grid 并在 Grid 中定义您的 InputBindings。在 canExecute-definition 中,您应该检查是否选择了一行。这也适用于 KeyBinding,例如自定义 Delete-Command。

<Grid>
        <Grid.InputBindings>
            <MouseBinding MouseAction="LeftDoubleClick" Command="... />
        </Grid.InputBindings>
        <DataGrid IsReadOnly="True">
        ...
</Grid>
于 2011-07-21T08:22:40.967 回答