如何在更改DataGrid.ItemsSource时引发事件

我是WPF的新手,我正在使用DataGrids,我需要知道属性ItemsSource何时被更改。

例如,我需要在执行此指令时必须引发事件:

dataGrid.ItemsSource = table.DefaultView; 

或者添加一行时。

我试过使用这段代码:

 CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items); ((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged); 

但此代码仅在用户向集合中添加新行时才有效。 因此,当整个ItemsSource属性发生任何更改时,我需要引发一个事件,因为整个集合被替换或者因为添加了一行。

我希望你能帮助我。 先感谢您

ItemsSource是一个依赖属性,因此当属性更改为其他属性时,很容易得到通知。 除了代码之外,您还希望使用此代码,而不是:

Window.Loaded (或类似)中,您可以这样订阅:

 var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid)); if (dpd != null) { dpd.AddValueChanged(myGrid, ThisIsCalledWhenPropertyIsChanged); } 

并有一个变更处理程序:

 private void ThisIsCalledWhenPropertyIsChanged(object sender, EventArgs e) { } 

每当设置ItemsSource属性时, ThisIsCalledWhenPropertyIsChanged调用ThisIsCalledWhenPropertyIsChanged方法。

您可以将此用于要通知更改的任何依赖项属性。

这有什么帮助吗?

 public class MyDataGrid : DataGrid { protected override void OnItemsSourceChanged( IEnumerable oldValue, IEnumerable newValue) { base.OnItemsSourceChanged(oldValue, newValue); // do something here? } protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); switch (e.Action) { case NotifyCollectionChangedAction.Add: break; case NotifyCollectionChangedAction.Remove: break; case NotifyCollectionChangedAction.Replace: break; case NotifyCollectionChangedAction.Move: break; case NotifyCollectionChangedAction.Reset: break; default: throw new ArgumentOutOfRangeException(); } } } 

如果您想要检测添加的新行,可以尝试DataGrid的InitializingNewItemAddingNewItem事件。

InitializingNewItem用法:

Datagrid自动添加包含父数据的项目