I wish to recalculate things everytime a DataGrid gets more rows or some are removed. I tried to use the Loaded
event, but that was fired only once.
I found
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;
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().Subscribe(DoWork);
// Broadcast
eventAggregator.GetEvent().Publish();
Using Messenger
//Subscribe
Messenger.Default.Register(DoWork);
// Broadcast
Messenger.Default.Send()