How to raise an event when DataGrid.ItemsSource is changed

Dante picture Dante · May 22, 2012 · Viewed 31.1k times · Source

I am new in WPF, and I am working with DataGrids and I need to know when the property ItemsSource is changed.

For example, I would need that when this instruction is executed an event has to raise:

dataGrid.ItemsSource = table.DefaultView;

Or when a row is added.

I have tried to use this code:

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

But this code works only when the user adds a new row to the collection. Therefore I need a event that be raised when the entire ItemsSource property has any change, either because the entire collection is replaced or because a single row is added.

I hope you can help me. Thank you in advance

Answer

vcsjones picture vcsjones · May 22, 2012

ItemsSource is a dependency property, so it's easy enough to be notified when the property is changed to something else. You would want to use this in addition to code that you have, not instead of:

In Window.Loaded (or similar) you can subscribe like so:

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

And have a change handler:

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

Whenever the ItemsSource Property is set, the ThisIsCalledWhenPropertyIsChanged method is called.

You can use this for any dependency property you want to be notified about changes.