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.
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!