如何使用Delete键从DataGrid中删除行

时间:2016-04-03 17:01:40

标签: c# wpf xaml datagrid

我有一个DataGrid并且里面有一些记录。我想要的是,当我按下键盘上的Delete键时,该行将被删除,甚至集合中的记录也会被删除。

我认为CanUserDeleteRows参数会起作用,但它不起作用。当我按删除时,该行消失,但仍保留在集合中。

这是我的DataGrid

<DataGrid 
   Name="ProjectsGrid" 
   ItemsSource="{Binding Path=FilesCollection}" 
   AutoGenerateColumns="False" 
   CanUserAddRows="False"  
   CanUserDeleteRows="True">
   <DataGrid.Columns>
      <DataGridCheckBoxColumn Header="Use" Binding="{Binding Include}"/>
      <DataGridTextColumn Header="Name" Binding="{Binding Path, Converter={StaticResource PathConverter}}"/>
   </DataGrid.Columns>
</DataGrid>

这是我的ViewModel:

namespace Validator.ViewModels
{
  class SettingsVm : INotifyPropertyChanged
  {
    public void ChangeProperty(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<CsprojFile> FilesCollection { get; set;} 
    public SettingsVM()
    {
        FilesCollection = new ObservableCollection<CsprojFile>();
   }
}

我是否必须向ViewModel添加一些事件?还是有其他一些我不知道的方式?

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您希望从View更新您的收藏,那么您应该将ItemSource的绑定模式提及为:

<DataGrid 
   Name="ProjectsGrid" 
   ItemsSource="{Binding Path=FilesCollection, Mode=TwoWay}" 
   AutoGenerateColumns="False" 
   CanUserAddRows="False"  
   CanUserDeleteRows="True">
            <DataGrid.Columns>
                <DataGridCheckBoxColumn Header="Use" Binding="{Binding Include}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Path}"/>
            </DataGrid.Columns>
        </DataGrid>

这可以解决您的问题