简体   繁体   中英

How do I get a datagrid that is bound to an observable collection to notify of deletions using mvvm?

I have a datagrid which is bound to an observable collection. I would like to know when a row (or multiple rows) are deleted from the datagrid. I'm trying to do this using mvvm.

I'm not worried about properties changing (its all read-only) just deletions. So I know I just need to use the CollectionChanged event. However not sure how I wire this up, especially using mvvm.

Datagrid

<DataGrid Grid.Row="0"
          ItemsSource="{Binding BookList, UpdateSourceTrigger=PropertyChanged}"
          Style="{StaticResource DataGridTemplate1}"
          ColumnHeaderStyle="{StaticResource DG_ColumnHeaderCenter1}"                                            
          RowStyle="{StaticResource DG_Row1}"
          CellStyle="{StaticResource DG_Cell1}"                                    
          RowHeaderStyle="{StaticResource DG_RowHeader1}"
          AutoGenerateColumns="False"
          HorizontalAlignment="Stretch" 
          CanUserDeleteRows="True"                          
          Background="Silver"
          RowHeaderWidth="30">
    <DataGrid.Columns>
        <DataGridTextColumn Header="DatePrice" IsReadOnly="True" Binding="{Binding DatePrice, StringFormat={}\{0:dd-MMM-yy\}}" MinWidth="75"/>
        <DataGridTextColumn Header="ISIN" IsReadOnly="True" Binding="{Binding ISIN}" MinWidth="75"/>
        <DataGridTextColumn Header="Name" IsReadOnly="True" Binding="{Binding Name}" MinWidth="75"/>
        <DataGridTextColumn Header="Price" IsReadOnly="True" Binding="{Binding Price, StringFormat={}{0:N0}}" MinWidth="75"/>                           
    </DataGrid.Columns>
</DataGrid>

You can write something like this. The event occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

BookList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( BookList_CollectionChanged );

void BookList_CollectionChanged( object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e )
{
    if ( e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove )
    {

    }
}

Implement INotifyPropertyChanged

use this

  public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

then in your Collection's(ItemsSource of DataGrid) Setter, add

OnPropertyChanged("CollectionName");

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