如何获得绑定到可观察集合的数据网格,以使用mvvm通知删除

本文关键字:网格 删除 通知 mvvm 数据网 数据 绑定 何获得 观察 集合 | 更新日期: 2023-09-27 18:27:40

我有一个绑定到可观察集合的数据网格。我想知道何时从数据网格中删除一行(或多行)。我正在尝试使用mvvm来实现这一点。

我不担心属性更改(全部为只读),只担心删除。所以我知道我只需要使用CollectionChanged事件。然而,我不确定我是如何连接的,尤其是使用mvvm。

数据网格

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

如何获得绑定到可观察集合的数据网格,以使用mvvm通知删除

你可以写这样的东西。当添加、删除、更改、移动项目或刷新整个列表时,会发生该事件。

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 )
    {
    }
}

实现INotifyPropertyChanged

使用这个

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

然后在Collection的(ItemsSource of DataGrid)Setter中,添加

OnPropertyChanged("CollectionName");