我正在寻找一个干净而优雅的解决方案,用于处理嵌套(子)对象的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这样的后构建步骤来完成我的目标。
BestFriend
的值。 - Marc Gravell