我已经对 stackoverflow 进行了一些研究和其他答案,表明我需要扩展 ObservableCollection 类以在添加或删除项目时向每个项目添加 PropertyChanged 事件处理程序,以便在集合中项目的内容发生变化时获取事件。 .. 真的有点烦人,但我已经根据其中一些答案实现了这个类:
public class DeeplyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public DeeplyObservableCollection()
: base()
{
CollectionChanged += new NotifyCollectionChangedEventHandler(DeeplyObservableCollection_CollectionChanged);
}
void DeeplyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
(item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
(item as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
}
}
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(a);
}
}
据我了解,当任何一个元素触发 PropertyChanged 事件时,都会触发 CollectionChanged 事件。当我从 item_PropertyChanged 方法进入 DeeplyObservableCollection_CollectionChanged 方法时,这似乎可以工作。
因此,在我的代码中,我将事件处理程序附加到 DeeplyObservableCollection_CollectionChanged 方法,如下所示:
GroupSettingsList.CollectionChanged += new NotifyCollectionChangedEventHandler(this.ContentCollectionChanged);
GroupSettingsList 是一个 DeeplyObservableCollection,而 ContentCollectionChanged 是一个 CollectionChanged 事件处理程序。我没有收到任何错误,但我的方法永远不会被调用,我不知道为什么。
我需要做什么才能在此处调用我的事件处理程序?
显示我如何使用此类的附加代码:
class MyViewModel : ViewModelBase
{
private DeeplyObservableCollection<GroupSettings> _groupSettingsList;
public MyViewModel()
{
GroupSettingsList = new DeeplyObservableCollection<GroupSettings>();
GroupSettingsList.CollectionChanged += new NotifyCollectionChangedEventHandler(this.ContentCollectionChanged);
// Have also tried this:
// _groupSettingsList.CollectionChanged += new NotifyCollectionChangedEventHandler(this.ContentCollectionChanged);
}
public class GroupSettings : INotifyPropertyChanged
{
private bool _isDisplayed;
public bool IsDisplayed
{
get { return _isDisplayed; }
set
{
_isDisplayed = value;
this.OnPropertyChanged("IsDisplayed");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
public DeeplyObservableCollection<GroupSettings> GroupSettingsList
{
get { return _groupSettingsList; }
set
{
_groupSettingsList = value;
this.OnPropertyChanged("GroupSettingsList");
}
}
private void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
DoSomething(); // This never executes.
}
}