Passing a Command Parameter from a Datagrid through a Keybinding

OnTheFly picture OnTheFly · Nov 21, 2011 · Viewed 16.6k times · Source

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.

Answer

H.B. picture H.B. · Nov 21, 2011

If your DataGrid has a name you can try to target it that way:

<KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"
            CommandParameter="{Binding SelectedItem, ElementName=myDataGrid}"/>

(Note: CommandParameter is only bindable in .NET 4 (and presumably the following versions) as it was changed into a dependency property)