我已经对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.
}
}