我在C#代码中的数据网格上有以下内容:
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding CmdTransUnitFillerRowDblClick}" />
</DataGrid.InputBindings>
除了用户首先选择行(单击)然后尝试双击该行之外,它大部分都有效。在这种情况下,CmdTransUnitFillerRowDblClick代码永远不会被触发进行处理。
那么,当行已被选中时,如何在双击时正确触发CmdTransUnitFillerRowDblClick?
因为有人可能会问:
private void ExecutecmdTransUnitFillerRowDblClick(object parameter)
{
if (DgTransUnitFillerSelectedItem != null)
TransUnitFillerDoubleClick(DgTransUnitFillerSelectedItem.CollectionRowId);
}
答案 0 :(得分:2)
见my answer to another related question。问题是数据网格在用户选择行(或实际上是单元格)之后不再具有焦点;用户在数据网格中单击的单元格。因此,您必须将焦点更改回datagrid以允许此操作。
变化:
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding CmdTransUnitFillerRowDblClick}" />
</DataGrid.InputBindings>
要:
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding CmdTransUnitFillerRowDblClick}" />
<MouseBinding Gesture="LeftClick" Command="{Binding CmdTransUnitFillerRowClick}" />
</DataGrid.InputBindings>
...并添加:
private void ExecutecmdTransUnitFillerRowClick(object parameter)
{
if (DgTransUnitFillerSelectedItem != null)
The_Name_Of_Your_DataGrid.Focus();
}
答案 1 :(得分:0)
在现有的InputBinding之上,您可以使用Style将InputBinding附加到每个单元格:
<Style TargetType="DataGridCell">
<Setter Property="local:MouseCommands.LeftDoubleClick" Value="ApplicationCommands.New" />
</Style>
这需要使用here中的MouseCommands类。
public static class MouseCommands
{
private static void LeftDoubleClickChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var control = (Control)sender;
if (args.NewValue != null && args.NewValue is ICommand)
{
var newBinding = new MouseBinding(args.NewValue as ICommand, new MouseGesture(MouseAction.LeftDoubleClick));
control.InputBindings.Add(newBinding);
}
else
{
var oldBinding = control.InputBindings.Cast<InputBinding>().First(b => b.Command.Equals(args.OldValue));
control.InputBindings.Remove(oldBinding);
}
}
public static readonly DependencyProperty LeftDoubleClickProperty =
DependencyProperty.RegisterAttached("LeftDoubleClick",
typeof(ICommand),
typeof(MouseCommands),
new UIPropertyMetadata(LeftDoubleClickChanged));
public static void SetLeftDoubleClick(DependencyObject obj, ICommand value)
{
obj.SetValue(LeftDoubleClickProperty, value);
}
public static ICommand GetLeftDoubleClick(DependencyObject obj)
{
return (ICommand)obj.GetValue(LeftDoubleClickProperty);
}
}
虽然我认为更简洁的方法是在代码隐藏中处理MouseDoubleClick事件,并通过直接调用ViewModel或在命令上调用.Execute()手动提升命令执行。