简体   繁体   中英

How to delete row from DataGrid with Delete key

I have a DataGrid and in it some records. What I want is, when I press Delete key on keyboard, the row gets deleted and even the record in collection is deleted.

I thought that the parameter CanUserDeleteRows would do the trick, but it doesn't work. When I press delete, the row disapears, but still remains in the collection.

This is my 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:

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? 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 :

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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