c# – 添加/删除行时,WPF DataGrid是否会触发事件?
发布时间:2020-12-15 04:28:27 所属栏目:百科 来源:网络整理
导读:每当DataGrid获取更多行或删除一些行时,我希望重新计算内容.我尝试使用Loaded事件,但只触发了一次. 我找到了 AddingNewItem ,但是在添加它之前就已经解雇了.之后我需要做我的事情. 还有LayoutUpdated,它可以使用,但我担心使用它是不明智的,因为它经常用于我
每当DataGrid获取更多行或删除一些行时,我希望重新计算内容.我尝试使用Loaded事件,但只触发了一次.
我找到了 还有LayoutUpdated,它可以使用,但我担心使用它是不明智的,因为它经常用于我的目的. 解决方法
如果您的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 } 另一种解决方案是使用事件系统,如Microsoft Prism的EventAggregator或MVVM Light的Messenger.这意味着只要绑定集合发生更改,ViewModel就会广播DataCollectionChanged事件消息,并且View会订阅接收这些消息并在任何时候执行代码. 使用EventAggregator // Subscribe eventAggregator.GetEvent<CollectionChangedMessage>().Subscribe(DoWork); // Broadcast eventAggregator.GetEvent<CollectionChangedMessage>().Publish(); 使用Messenger //Subscribe Messenger.Default.Register<CollectionChangedMessage>(DoWork); // Broadcast Messenger.Default.Send<CollectionChangedMessage>() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |