如何使用MVVM绑定键盘删除键

时间:2018-05-30 07:12:49

标签: wpf mvvm-light

我在viewmodel中有一个relaycommand。

 DeleteCommand = new RelayCommand<Customer>(param =>
  {
 //my code
  });

我将此命令绑定到一个按钮,我想将其绑定到删除键。

<KeyBinding  Key="Delete"
        Command="{Binding DeleteCommand}" CommandParameter="{Binding SelectedItem, ElementName=CustomerListView}"/>

它是按钮上的工作,但不能用于删除键。

<DataGrid Margin="10" CanUserDeleteRows="False" CellStyle="{StaticResource MaterialDesignDataGridCell}" Height="310" Name="CustomerListView"  filter:DataGridExtensions.UseBackgroundWorkerForFiltering="True"
    filter:DataGridExtensions.IsClearButtonVisible="False" IsReadOnly="True"
   filter:DataGridExtensions.IsFilterVisible="True"
   ColumnHeaderStyle="{StaticResource {ComponentResourceKey 
    TypeInTargetAssembly={x:Type filter:DataGridHeaderFilterControl}, 
    ResourceId=DataGridHeaderFilterControlStyle}}"
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=CustomerCollection}" >
     <DataGrid.Columns>
      <DataGridTextColumn  Width="100" Header="Code" Binding="{Binding Path=Code}"/>
      <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="200"/>
      </DataGrid.Columns>
   <i:Interaction.Triggers>
   <i:EventTrigger EventName="MouseDoubleClick">
    <command:EventToCommand Command="{Binding EditCommand}" CommandParameter="{Binding SelectedItem, ElementName=CustomerListView}" />
   </i:EventTrigger>
  </i:Interaction.Triggers>
</DataGrid>

1 个答案:

答案 0 :(得分:2)

简单的馅饼:

<Window.InputBindings>
    <KeyBinding Key="Delete" Command="{Binding DeleteCommand}"/>
</Window.InputBindings>

有关详细信息,请查看HERE