我有一个可观察的viewmodel对象集合。如何在创建集合时订阅我的集合中每个视图模型的Property Changed事件,并跟踪哪些已更改,以便我可以将它们更新到我的数据库。
答案 0 :(得分:2)
我相信下面的代码可以作为解决问题的一个例子。在此示例中,MyCollection是一个属性ViewModel对象。 ViewModel实现了INotifyPropertyChanged接口。
private void AddCollectionListener()
{
if (MyCollection != null)
{
MyCollection.CollectionChanged +=
new System.Collections.Specialized.NotifyCollectionChangedEventHandler(MyCollection_CollectionChanged);
}
}
void MyCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Remove Listeners to each item that has been removed
foreach (object oldItem in e.OldItems)
{
ViewModel viewModel = oldItem as ViewModel;
if (viewModel != null)
{
viewModel.PropertyChanged -= viewModel_PropertyChanged;
}
}
// Add Listeners to each item that has been added
foreach (object newItem in e.NewItems)
{
ViewModel viewModel = newItem as ViewModel;
if (viewModel != null)
{
viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged);
}
}
}
void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// TODO: Property Changed Logic
switch (e.PropertyName)
{
case "MyPropertyName":
// TODO: Perform logic necessary when MyPropertyName changes
break;
default:
// TODO: Perform logic for all other property changes.
break;
}
}