有谁知道为什么这段代码行不通:
public class CollectionViewModel : ViewModelBase { public ObservableCollection<EntityViewModel> ContentList { get { return _contentList; } set { _contentList = value; RaisePropertyChanged("ContentList"); //I want to be notified here when something changes..? //debugger doesn't stop here when IsRowChecked is toggled } } } public class EntityViewModel : ViewModelBase { private bool _isRowChecked; public bool IsRowChecked { get { return _isRowChecked; } set { _isRowChecked = value; RaisePropertyChanged("IsRowChecked"); } } }
ViewModelBase包含所有内容,RaisePropertyChanged等等。除了此问题外,它还可用于其他所有内容。
ViewModelBase
RaisePropertyChanged
当您更改集合内的值时,不会调用ContentList的Set方法,而是应该注意CollectionChanged事件触发。
public class CollectionViewModel : ViewModelBase { public ObservableCollection<EntityViewModel> ContentList { get { return _contentList; } } public CollectionViewModel() { _contentList = new ObservableCollection<EntityViewModel>(); _contentList.CollectionChanged += ContentCollectionChanged; } public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { //This will get called when the collection is changed } }
好的,那是今天我被MSDN文档写错了。在我给您的链接中,它说:
在添加,删除,更改,移动项目或刷新整个列表时发生。
但是更改项目时实际上 不会 触发。我猜您将需要一个更强力的方法:
public class CollectionViewModel : ViewModelBase { public ObservableCollection<EntityViewModel> ContentList { get { return _contentList; } } public CollectionViewModel() { _contentList = new ObservableCollection<EntityViewModel>(); _contentList.CollectionChanged += ContentCollectionChanged; } public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Remove) { foreach(EntityViewModel item in e.OldItems) { //Removed items item.PropertyChanged -= EntityViewModelPropertyChanged; } } else if (e.Action == NotifyCollectionChangedAction.Add) { foreach(EntityViewModel item in e.NewItems) { //Added items item.PropertyChanged += EntityViewModelPropertyChanged; } } } public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) { //This will get called when the property of an object inside the collection changes } }
如果您非常需要此功能,则可能需要将自己的子类化ObservableCollection,CollectionChanged当成员PropertyChanged自动触发事件时触发事件的子类(如文档中应该说的那样)。
ObservableCollection
CollectionChanged
PropertyChanged