[英]Observable Collection within a Property of Another Class
假设我有一个实现INotifyPropertyChanged
的类,其中一个属性是一个成员为ObservableCollections
的类:
namespace Example
{
public class A : INotifyPropertyChanged
{
private B _prop;
public B Prop
{
get { return _prop; }
set
{
_prop = value;
NotifyPropertyChanged("Prop");
}
}
public A() { Prop = new B(); }
//"Some Property" related Prop.words
}
public class B
{
public ObservableCollection<String> words { get; set; }
public B() { words = new ObservableCollection<String>(); }
}
}
我对如何在Prop.words
更改时如何通知A
类中A
该属性感到困惑。 我应在哪个类中实现INotifyCollectionChanged
的处理程序?
编辑:我之前没有指定上下文,但是我绑定了Prop.words
更改时需要更新的“某些属性”上的WPF控件。
如果需要通知A类,则只需要在A类中挂接CollectionChanged 。 在属性设置器中执行此操作。
确保在属性B被设置为新值的情况下解钩处理程序,以避免任何内存泄漏。
public class A : INotifyPropertyChanged
{
private B _prop;
public B Prop
{
get { return _prop; }
set
{
if(_prop != null)
_prop.words.CollectionChanged -= words_CollectionChanged;
_prop = value;
if (_prop != null)
_prop.words.CollectionChanged += words_CollectionChanged;
NotifyPropertyChanged("Prop");
}
}
void words_CollectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
// Notify other properties here.
}
public A() { Prop = new B(); }
//Some Property related Prop.words
}
A
类的客户应处理此问题。
当基础集合更改破坏INotifyPropertyChanged
的功能约定时,恕我直言,将PropertyChanged
更改为INotifyPropertyChanged
。
此外,假设您有一个绑定到集合的项目控件:每次更改集合时,它都会完全反弹,因为我们通知您它已完全更改,绝对不是您想要的!
A a = new A();
...
a.Prop.Words.CollectionChanged += ...
如果绑定到Prop
属性,这正是WPF控件将执行的操作。
请注意,从教条化的OO设计角度来看,这违反了Demeter定律,因此您可以将Words集合表面放入A类型以避免这种情况,但这是另一个问题/辩论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.