添加/删除行时,WPF DataGrid是否会触发事件?

Tow*_*wer 7 .net c# wpf

每当DataGrid获取更多行或删除一些行时,我希望重新计算内容.我试图使用该Loaded事件,但只被触发一次.

我找到了AddingNewItem,但是在添加它之前就已经解雇了.我需要做我的东西之后.

还有LayoutUpdated,它有效,但我担心使用它是不明智的,因为它经常为我的目的而开火.

Rac*_*hel 9

如果你DataGrid受某种约束,我想到了两种方法.

您可以尝试获取该DataGrid.ItemsSource集合,并订阅其CollectionChanged活动.这只有在你知道它首先是什么类型的集合时才有效.

// 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
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用事件系统,如Microsoft Prism EventAggregator或MVVM Light Messenger.这意味着您ViewModel可以DataCollectionChanged在绑定集合发生更改时随时广播事件消息,并且您View可以订阅接收这些消息并在任何时候执行代码.

运用 EventAggregator

// Subscribe
eventAggregator.GetEvent<CollectionChangedMessage>().Subscribe(DoWork);

// Broadcast
eventAggregator.GetEvent<CollectionChangedMessage>().Publish();
Run Code Online (Sandbox Code Playgroud)

运用 Messenger

//Subscribe
Messenger.Default.Register<CollectionChangedMessage>(DoWork);

// Broadcast
Messenger.Default.Send<CollectionChangedMessage>()
Run Code Online (Sandbox Code Playgroud)