コレクション内のアイテムの内容が変更されたときにイベントを取得するために、アイテムが追加または削除されたときに各アイテムに PropertyChanged イベントハンドラーを追加するには、ObservableCollection クラスを拡張する必要があることをスタックオーバーフローに関するいくつかの調査と他の回答で示しました。 ..本当に少し面倒ですが、これらの回答のいくつかに基づいてこのクラスを実装しました:
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);
}
}
私が理解しているように、CollectionChanged イベントは、要素の 1 つが PropertyChanged イベントを発生させるたびに発生します。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.
}
}