Does WPF DataGrid fire an event when a row is added / removed?

前端 未结 7 607
失恋的感觉
失恋的感觉 2021-02-06 05:48

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

7条回答
  •  北海茫月
    2021-02-06 06:45

    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()
    

提交回复
热议问题