Does WPF DataGrid fire an event when a row is added / removed?
If your DataGrid
is bound to something, I think of two ways of doing this.
You could try getting the DataGrid.ItemsSource
collection, and subscribing to its CollectionChanged
event. This will only work if you know what type of collection it is in the first place.
// Be warned that the `Loaded` event runs anytime the window loads into view,
// so you will probably want to include an Unloaded event that detaches the
// collection
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
var dg = (DataGrid)sender;
if (dg == null || dg.ItemsSource == null) return;
var sourceCollection = dg.ItemsSource as ObservableCollection<ViewModelBase>;
if (sourceCollection == null) return;
sourceCollection .CollectionChanged +=
new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged);
}
void DataGrid_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Execute your logic here
}
The other solution would be to use an Event System such as Microsoft Prism's EventAggregator
or MVVM Light's Messenger
. This means your ViewModel
would broadcast a DataCollectionChanged
event message anytime the bound collection changes, and your View
would subscribe to receive these messages and execute your code anytime they occur.
Using EventAggregator
// Subscribe
eventAggregator.GetEvent<CollectionChangedMessage>().Subscribe(DoWork);
// Broadcast
eventAggregator.GetEvent<CollectionChangedMessage>().Publish();
Using Messenger
//Subscribe
Messenger.Default.Register<CollectionChangedMessage>(DoWork);
// Broadcast
Messenger.Default.Send<CollectionChangedMessage>()
How about DataGrid.LoadingRow(object sender, DataGridRowEventArgs e)
?
Same for Unloading.
DataGrid.UnLoadingRow(object sender, DataGridRowEventArgs e)
?
Have you tried an MVVM approach and binding to an Observable collection?
public ObservableCollection<Thing> Items{
get { return _items; }
set{ _items = value; RaisePropertyChanged("Items"); // Do additional processing here
}
}
So you can watch the add / remove of items without being tied to the UI?