通过键绑定从Datagrid传递命令参数

OnT*_*Fly 4 wpf xaml key-bindings commandparameter

我有一个特定的wpf问题.我正在尝试从Datagrid中删除一行,方法是定义一个Keybinding,它将Datagrid的选定行作为CommandParameter传递给Command.

这是我的Keybinding:

<UserControl.Resources >
    <Commands:CommandReference x:Key="deleteKey" Command="{Binding DeleteSelectedCommand}"/>
</UserControl.Resources>

<UserControl.InputBindings>
    <KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"/>
</UserControl.InputBindings>
Run Code Online (Sandbox Code Playgroud)

我知道这基本上有效,因为我可以调试到DeleteSelectedCommand.但是有一个异常,因为DeleteSelectedCommand会将Datagrid的一行预先删除为Call Parameter.

如何通过Keybinding传递SelectedRow?

我想在可能的情况下仅在XAML中执行此操作,而不更改Code Behind.

H.B*_*.B. 11

如果您的DataGrid有一个名称,您可以尝试以这种方式定位它:

<KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"
            CommandParameter="{Binding SelectedItem, ElementName=myDataGrid}"/>
Run Code Online (Sandbox Code Playgroud)

(注意:CommandParameter只能在.NET 4中绑定(可能是以下版本),因为它已被更改为依赖属性)


小智 2

不要尝试使用命令参数,而是创建一个属性来存储所选行:

private Model row;

 public Model Row
     {
         get { return row; }
         set
         {
             if (row != value)
             {
                 row = value;
                 base.RaisePropertyChanged("Row");
             }
         }
     }
Run Code Online (Sandbox Code Playgroud)

其中 Model 是网格显示的对象的类。在数据网格上添加 selectedItem 属性以使用该属性:

<DataGrid SelectedItem="{Binding Row, UpdateSourceTrigger=PropertyChanged}"/> 
Run Code Online (Sandbox Code Playgroud)

然后让您的命令通过行传递到方法:

    public ICommand DeleteSelectedCommand
     {
         get
         {
             return new RelayCommand<string>((s) => DeleteRow(Row));
         }
     }
Run Code Online (Sandbox Code Playgroud)

对于您的键绑定:

 <DataGrid.InputBindings>
            <KeyBinding Key="Delete" Command="{Binding DeleteSelectedCommand}" />
        </DataGrid.InputBindings>
Run Code Online (Sandbox Code Playgroud)

希望有帮助!