【发布时间】:2017-12-06 11:37:47
【问题描述】:
我已经为 ObservableCollection 实现了 CollectionChanged,就像这里一样: Implementing CollectionChanged
是否有可能在 OnCollectionChanged 方法中找出更改的属性的名称是什么?
编辑: 如果班级有任何变化,则应编写历史记录。 我想实现三种情况:
- “正常”属性已更改(字符串、整数、...):这已经是 工作
- 在集合中添加和删除:如果我知道更改集合的名称,将会工作
-
集合内的属性已更改:与 2 相同的问题)我不知道 ch 的名称(和索引)
public class ParentClass : BaseModel { public ParentClass() { Children = new ObservableCollection<SomeModel>(); Children.CollectionChanged += Oberservable_CollectionChanged; } private string id; public string Id { get { return id; } set { string oldId = id; id = value; OnPropertyChanged(oldArticleId,id); } } public ObservableCollection<SomeModel> Children { get; set; } protected virtual void OnPropertyChanged(object oldValue, object newValue, [CallerMemberName] string propertyName = null) { //1) Entry is added to history (this part is working) } protected void Oberservable_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) { foreach (INotifyPropertyChanged added in e.NewItems) { added.PropertyChanged += OnPropertyChangedHandler; OnCollectionChanged(CollectionChangedModel.Action.Added, added); } } if (e.OldItems != null) { foreach (INotifyPropertyChanged removed in e.OldItems) { removed.PropertyChanged -= OnPropertyChangedHandler; OnCollectionChanged(CollectionChangedModel.Action.Removed, removed); } } } protected virtual void OnCollectionChanged(CollectionChangedModel.Action action, object value) { //2) TODO: History should be written, but I don't have the property name } public void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { //3) TODO: History about changed property in child-class (not working because of missing property name and index) } }
【问题讨论】:
-
如果我错了,请纠正我,但
collectionChanged不是打算在 collection 更改时通知我,而不是 collection 中的项目我>? -
那不是一个 CollectionChanged 实现,那是一个事件监听器。你确实知道是谁提出了这个事件——你得到
sender作为参数 -
@TimothyGroote:是的,但是集合是另一个类中的属性,我需要知道这个属性的名称(集合的名称)
-
@Pinzi 然后 that 类必须实现 INotifyPropertyChanged 并且您应该监听该接口并处理其事件。如果您使用数据竞价,您实际上无需执行任何操作。设置数据绑定时,控件会自动订阅通知
标签: c# inotifycollectionchanged