我使用包含模型类 B 列表的模型类 A。每个模型(A 和 B)都实现 INotifyPropertyChanged,并且在属性更改时正确触发事件。模型 A 已从模型 B 订阅了此事件,如果发生此事件,模型 A 会触发另一个更改的属性。
我的问题是我想在应该将更改写入数据库的服务类中侦听模型 A(包括嵌套模型属性)中的更改。但是当模型 A 触发 propertychanged 时,在我的服务类中,我无法知道已更改的属性是属于模型 A 还是属于模型 B 之一。
public class Model B : ObservableObject
{
...
public int Property1
{
get{return property1;}
set{ this.property1 = value;
OnPropertyChanged("Property1");
}
}
}
public class ModelA : ObservableObject
{
...
ObservableCollection<ModelB> modelsB;
...
public ObservableCollection<ModelB> ModelsB
{
get
{
if(modelsB == null)
{
this.modelsB = new ObservableCollection<ModelB>();
this.modelsB.CollectionChanged+= ModelBListChanged;
}
return modelsB;
}
}
private int property2;
public int Property2
{
get{return property2;}
set{ this.property2 = value;
OnPropertyChanged("Property2");
}
}
private void ModelBListChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if(e.NewItems != null)
{
foreach(ObservableObject item in e.NewItems)
{
item.PropertyChanged += NotifyPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (ObservableObject item in e.OldItems)
{
item.PropertyChanged -= NotifyPropertyChanged;
}
}
}
...
}
public class SomeService
{
...
ObservableCollection<ModelA> modelsA;
public ObservableCollection<ModelA> ModelsA
{
get
{
if(modelsA == null)
{
modelsA = new ObservableCollection<ModelA>();
//fill with data...
....
foreach(...)
{
ModelB mb = new ModelB();
//fill mb ...
...
mb.PropertyChanged += ModelBChanged;
modelsA.ModelsB.Add(mb);
}
....
modelsA.PropertyChanged += ModelsAChanged;
}
return modelsA;
}
}
...
private void ModelsAChanged(object sender, PropertyChangedEventArgs args)
{
// determine the property that has changed and call the correct
// update function for this property to write the data to database.
var ma = (ModelA) sender;
switch(args.PropertyName)
{
...
case ModelA.Property1:
//update database with function for property 1
break;
case ModelA.Property2:
//update database with function for property 2
break;
...
}
}
private void ModelBChanged(object sender, PropertyChangedEventArgs args)
{
// How do I know to which ModelA this ModelB sender belongs?
var mb = (ModelB) sender;
switch(args.PropertyName)
{
...
case ModelB.Property1:
//update database with function for property 1 of model B
break;
...
}
}
}
这怎么可能解决?
问候,
塔比纳