【发布时间】:2011-05-07 18:57:01
【问题描述】:
我正在寻找一种干净且优雅的解决方案来处理嵌套(子)对象的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 属性和它的值设置器。现在我知道我可以手动执行此操作,实现 cmets 中描述的所有步骤。但这将是很多代码,尤其是当我计划让许多子属性像这样实现INotifyPropertyChanged 时。当然,它们并不总是相同的类型,它们唯一的共同点是INotifyPropertyChanged 接口。
原因是,在我的真实场景中,我有一个复杂的“Item”(在购物车中)对象,它在多个层上具有嵌套的对象属性(Item 有一个“License”对象,它本身可以再次具有子对象) 并且我需要收到有关“项目”的任何单一更改的通知,以便能够重新计算价格。
你有什么好的建议,甚至一些 实施帮助我解决 这个?
很遗憾,我无法/不允许使用 PostSharp 等后期构建步骤来实现我的目标。
【问题讨论】:
-
AFAIK,大多数绑定实现不期望事件以这种方式传播。毕竟,您没有更改
BestFriend的值。
标签: c# .net events inotifypropertychanged