有UserControl,除其他外,有DataGrid。
您需要从外部绑定命令,Enter如下所示:
<myControls:ProductsDataGrid.InputBindings>
<KeyBinding Key="Enter"
Command="{Binding OpenProductCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type myControls:ProductsDataGrid}}, Path=SelectedItem}" />
</myControls:ProductsDataGrid.InputBindings>
问题是它以自己的方式DataGrid处理点击,只是将选择从当前行转移到下一行。Enter
如果您更改密钥,那么一切都会正常运行。
如何实现期望的行为?
如果您DataGrid以这种方式绑定热键,则一切正常,但解决方案不可靠。
<DataGrid.InputBindings>
<KeyBinding Key="Enter"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ProductsDataGrid}}, Path=InputBindings[0].Command}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ProductsDataGrid}}, Path=InputBindings[0].CommandParameter}" />
</DataGrid.InputBindings>
事实上,您可以通过不同的方式解决这个问题,其中一种解决方案如下:
In
DataGrid,它位于您UserControl订阅的事件中PreviewKeyDown。接下来,在该事件的处理程序中,我们生成一个按键事件Enter。使用这种方法,将调用从外部绑定到用户控件的命令,同时
DataGrid不会将所选行移动到下一行。遇到了类似的问题。我使用 PreviewKeyDown 作为解决方案 - 我定义了自己的逻辑并关闭了 KeyDown 事件的进一步发生。
XAML:
从#:
也许,这种方法也可以用于 MVVM。