當您更改集合時,將調用您的setter,而不是集合的內容已更改。 您需要的是一個集合,通知您有關更改。看看ObservableCollection<T>
-課程。註冊到其CollectionChanged事件beeing通知變化。
與二傳手
下面的例子屬性顯示你如何能與持有可觀察集合設置屬性工作。該示例的複雜性是因爲可以從實例的外部設置集合。如果你不需要這個功能,解決方案將變得更加簡單。
private ObservableCollection<string> _items;
public ObservableCollection<string> Items {
get {
if (_items == null) {
// Create a new collection and subscribe to the event
Items=new ObservableCollection<string>();
}
return _items;
}
set {
if(value !=_items){
if (null != _items) {
// unsubscribe for the old collection
_items.CollectionChanged -= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_items_CollectionChanged);
}
_items = value;
if (null != _items) {
// subscribe for the new collection
_items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_items_CollectionChanged);
}
// Here you will be informed, when the collection itselfs has been changed
RaisePropertyChanged("Items");
}
}
}
void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
// Here you will be informed, if the content of the collection has been changed.
}
屬性,而不二傳手
如果你不需要有收藏可置,在創建集合註冊CollectionChanged
。然而,你必須刪除你的財產的二傳手。否則會如果集合已經改變不能改變的通知:
private ObservableCollection<string> _items;
public ObservableCollection<string> Items {
get {
if (_items == null) {
// Create a new collection and subscribe to the event
_items=new ObservableCollection<string>();
_items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler
}
return _items;
}
}
void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
// Here you will be informed, if the content of the collection has been changed.
}
信息
看INotifyCollectionChanged約收集變化的進一步信息。上面的例子,您也可以使用IEnumerable<string>
和INotifyCollectionChanged
更通用。
來源
2011-02-02 21:24:00
HCL