我有一个wpf特定的问题。 我试图从Datagrid中删除一行,方法是定义一个Keybinding,将所选的Datagrid行作为Command参数传递给Command。
这是我的键盘绑定:
<UserControl.Resources > <Commands:CommandReference x:Key="deleteKey" Command="{Binding DeleteSelectedCommand}"/> </UserControl.Resources> <UserControl.InputBindings> <KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"/> </UserControl.InputBindings>我知道这基本上可行,因为我可以调试到DeleteSelectedCommand。 但是,由于DeleteSelectedCommand会将数据行的行删除为Call Parameter,所以会出现异常。
如何通过键绑定传递SelectedRow?
我想在可能的情况下仅在XAML中执行此操作,而不更改Code Behind。
I've a wpf specific problem. I'm trying to delete a Row from a Datagrid, by defining a Keybinding that passes the selected Row of the Datagrid as a Commandparameter to a Command.
This is my 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>I know this basically works, because I can debug up to the DeleteSelectedCommand. However there flies an Exception because the DeleteSelectedCommand expectes a Row of the Datagrid to delete as Call Parameter.
How can I pass the SelectedRow through the Keybinding?
I want to do this only in the XAML, if possible, without changing the Code Behind.
最满意答案
与其尝试使用命令参数,不如创建一个属性来存储选定的行:
private Model row; public Model Row { get { return row; } set { if (row != value) { row = value; base.RaisePropertyChanged("Row"); } } }其中Model是网格显示的对象的类别。 在datagrid上添加selectedItem属性以使用该属性:
<DataGrid SelectedItem="{Binding Row, UpdateSourceTrigger=PropertyChanged}"/>然后让你的命令通过该行到该方法:
public ICommand DeleteSelectedCommand { get { return new RelayCommand<string>((s) => DeleteRow(Row)); } }并为您的键盘绑定:
<DataGrid.InputBindings> <KeyBinding Key="Delete" Command="{Binding DeleteSelectedCommand}" /> </DataGrid.InputBindings>希望有所帮助!
Rather than trying to use a command parameter, create a property to store the selected row in:
private Model row; public Model Row { get { return row; } set { if (row != value) { row = value; base.RaisePropertyChanged("Row"); } } }where Model is the class of the objects your grid is displaying. Add the selectedItem property on the datagrid to use the property:
<DataGrid SelectedItem="{Binding Row, UpdateSourceTrigger=PropertyChanged}"/>then have your command pass through the row to the method:
public ICommand DeleteSelectedCommand { get { return new RelayCommand<string>((s) => DeleteRow(Row)); } }and for your keybindings:
<DataGrid.InputBindings> <KeyBinding Key="Delete" Command="{Binding DeleteSelectedCommand}" /> </DataGrid.InputBindings>Hope that helps!
更多推荐
发布评论