是否WPF DataGrid中触发一个事件时,添加/删除行?事件、WPF、DataGrid

2023-09-04 23:12:03 作者:克制

我要重新计算的东西,每次DataGrid中得到更多的行或部分被删除。我试图用加载事件,但被触发一次。

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.

我发现 AddingNewItem ,但它已被添加之前被激发。我需要做我的东西的之后的。

还有 LayoutUpdated ,它的工作原理,但恐怕这不是明智的做法是使用它,因为它触发的方式往往为我的目的。

There's also LayoutUpdated, which works, but I'm afraid it's not wise to use it, because it fires way too often for my purposes.

推荐答案

如果你的的DataGrid 必然的东西,我认为这样做的两种方式。

If your DataGrid is bound to something, I think of a two ways of doing this.

您可以尝试获得 DataGrid.ItemsSource 的收集,并订阅了 Col​​lectionChanged 事件。这,如果你知道这是摆在首位是什么类型的集合才有效。

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
}

其他的解决办法是使用一个事件系统,如微软棱镜的 EventAggregator 或MVVM光的使者。这意味着你的视图模型将播出 DataCollectionChanged 事件消息随时绑定的集合改变,你的查看将订阅接收这些消息并执行他们的出现code随时随地。

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.

使用 EventAggregator

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

// Broadcast
eventAggregator.GetEvent<CollectionChangedMessage>().Publish();

使用使者

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

// Broadcast
Messenger.Default.Send<CollectionChangedMessage>()