If your DataGrid is related to something, I think of two ways to do it.
You can try to get the DataGrid.ItemsSource collection and subscribe 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 }
Another solution is to use an event system such as Microsoft Prism EventAggregator or MVVM Light Messenger . This means that your ViewModel will send a DataCollectionChanged event DataCollectionChanged every time the associated collection changes, and your View will 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>()
source share