2

在我的 Silverlight 4DataGrid控件中,我想附加一个非常简单的行为,它在按键上执行自定义命令 - 实际上,在按 ENTER 键时提交 DataGrid 中的选定项目。

虽然行为实际上有效(请参阅我的代码...

//.... in "OnAttached()..."
this.AssociatedObject.AddHandler(Control.KeyDownEvent, new KeyEventHandler(OnKeyDown), true);

private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            InvokeCommand();
        }
    }

...)我有一个问题,DataGrid 似乎自己处理 ENTER 键按下并继续到下一行。显然,发生的情况是提交了错误的行,因为当我处理按键时,行选择已经改变。

这是 XAML:

<data:DataGrid
      AutoGenerateColumns="False"
      IsReadOnly="True"
      ItemsSource="{Binding Path=Data}"
      SelectedItem="{Binding SelectedRow, Mode=TwoWay}">
   <data:DataGrid.Columns>
      <data:DataGridTextColumn Binding="{Binding A}" />
      <data:DataGridTextColumn Binding="{Binding B}" />
      <data:DataGridTextColumn Binding="{Binding C}" />
   </data:DataGrid.Columns>
   <i:Interaction.Behaviors>
      <behaviors:EnterBehavior Command="{Binding CommitCommand}" />
   </i:Interaction.Behaviors>
</data:DataGrid>

你能告诉我如何防止默认的 ENTER 事件吗?

4

3 回答 3

4

猜猜现在帮助 OP 有点晚了,但我通过子类化数据网格并覆盖 KeyDown 方法将 e.Handled 设置为 true 来解决这个问题。这会停止 DataGrid 的默认输入处理,然后您自己的操作才能生效。

(显然,您必须用 YourCustomDataGrid 替换 XAML 中的 DataGrid 实例)

public class YourCustomDataGrid : DataGrid
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Stop "Enter" selecting the next row in the grid
        if (e.Key == Key.Enter)
        {
            e.Handled = true;
        }
        base.OnKeyDown(e);
    }
}
于 2011-03-07T14:33:01.883 回答
1

不要依赖SelectedRow,首先使用引发事件的行作为提交操作的参数。请参见下面的代码:

private void OnKeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
    { 
        InvokeCommand(e.OriginalSource); 
    }
}
于 2011-12-19T10:31:20.787 回答
0

看看使用带有handledEventsToo 的AddHandler 重载是否可以帮助你。在某些情况下,这允许您调用您的处理程序,即使之前的处理程序已经设置了handled=true。

于 2011-02-21T13:42:41.930 回答