UPDATE:问题已解决,请参阅my Answer。为嵌套(子)对象订阅INotifyPropertyChanged
我在寻找一个干净,优雅的解决处理INotifyPropertyChanged
事件嵌套(子)对象。示例代码:
public class Person : INotifyPropertyChanged {
private string _firstName;
private int _age;
private Person _bestFriend;
public string FirstName {
get { return _firstName; }
set {
// Short implementation for simplicity reasons
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
public int Age {
get { return _age; }
set {
// Short implementation for simplicity reasons
_age = value;
RaisePropertyChanged("Age");
}
}
public Person BestFriend {
get { return _bestFriend; }
set {
// - Unsubscribe from _bestFriend's INotifyPropertyChanged Event
// if not null
_bestFriend = value;
RaisePropertyChanged("BestFriend");
// - Subscribe to _bestFriend's INotifyPropertyChanged Event if not null
// - When _bestFriend's INotifyPropertyChanged Event is fired, i'd like
// to have the RaisePropertyChanged("BestFriend") method invoked
// - Also, I guess some kind of *weak* event handler is required
// if a Person instance i beeing destroyed
}
}
// **INotifyPropertyChanged implementation**
// Implementation of RaisePropertyChanged method
}
专注于BestFriend
属性和它的价值设定器。现在我知道我可以手动执行此操作,执行评论中描述的所有步骤。但是这将会是很多代码,特别是当我计划拥有许多像这样实现INotifyPropertyChanged
的子属性时。当然,它们并不总是相同的类型,它们唯一共同的地方就是INotifyPropertyChanged
接口。
原因是,在我的真实场景中,我有一个复杂的“项目”(在购物车中)对象,它具有在多个图层上嵌套对象属性(Item有一个“License”对象,它本身可以有子对象再次),我需要得到有关“项目”的任何单一更改的通知才能重新计算价格。
你有些好的提示,甚至有些 执行帮我解决 这个?
不幸的是,我不能/允许使用PostSharp之类的构建后步骤来实现我的目标。
非常感谢你提前,
- 托马斯
AFAIK,大多数绑定实现不希望事件以这种方式传播。毕竟,你*还没有*改变过BestFriend的价值。 – 2010-11-10 10:09:41