[英]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.