在我的Silverlight 4 DataGrid
控件中,我想附加一个非常简单的行为,它在按键上执行自定义命令按 - 实际上,在按下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键按下它自己并进入下一行。显然,发生的是错误的Row被提交,因为当我处理Key Press时,行选择已经改变。
这是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事件吗?
答案 0 :(得分:4)
现在猜测它有点晚了,但是我通过继承数据网格并重写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);
}
}
答案 1 :(得分:1)
不要依赖SelectedRow
,首先使用引发事件的行作为提交操作的参数。请参阅以下代码:
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
InvokeCommand(e.OriginalSource);
}
}
答案 2 :(得分:0)
查看使用带有handleEventsToo的AddHandler overload是否可以为您提供帮助。在某些情况下,这允许您调用处理程序,即使先前的处理程序已设置processed = true。