简体   繁体   English

如何使用Delete键从DataGrid删除行

[英]How to delete row from DataGrid with Delete key

I have a DataGrid and in it some records. 我有一个DataGrid ,其中有一些记录。 What I want is, when I press Delete key on keyboard, the row gets deleted and even the record in collection is deleted. 我想要的是,当我按键盘上的Delete键时,该行将被删除,甚至收集中的记录也将被删除。

I thought that the parameter CanUserDeleteRows would do the trick, but it doesn't work. 我以为参数CanUserDeleteRows可以解决问题,但不起作用。 When I press delete, the row disapears, but still remains in the collection. 当我按Delete键时,该行消失,但仍保留在集合中。

This is my DataGrid : 这是我的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>

This is my ViewModel: 这是我的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>();
   }
}

Do I have to add some event to my ViewModel? 我是否必须向我的ViewModel添加一些事件? Or is there some other way I'm not aware of? 还是有其他我不知道的方式?

Thanks in advance. 提前致谢。

If you want your collection to be updated from View then you should mention binding mode for ItemSource as : 如果要从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>

This should solve your issue 这应该可以解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM