ObservableCollection PropertyChanged事件 [英] ObservableCollection PropertyChanged event

查看:209
本文介绍了ObservableCollection PropertyChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定,所以我想对ObservableCollection进行子类化,以向其添加属性.不幸的是PropertyChanged事件受到保护.基本上,我想对其进行子类化,使其具有SelectedItem,可以将其绑定到MVVM WPF应用程序中的列表中.

OK so I want to subclass ObservableCollection to add a property to it. Unfortunately the PropertyChanged event is protected. Basically I want to subclass it to have a SelectedItem that I can bind to for lists in my MVVM WPF app.

这是我班级的骨架:

public class SelectableList<T> : ObservableCollection<T>
{
    public T SelectedItem {get;set;}
}

但是我不能执行以下操作:

But I cannot do the following:

SelectableList<int> intList = new SelectableList<int>();
intList.PropertyChanged += new PropertyChangedEventHandler(intList_Changed);

由于访问限制.这使我提出了一个更深层次的问题.用户界面如何获得PropertyChanged事件(例如Count属性)的通知,而我却无法在代码隐藏中做到这一点?

because of access restrictions. This causes me to ask a deeper question. How come the UI can get notified of PropertyChanged events(e.g. Count property) and I can't do it in code-behind?

我的头在旋转,有人可以启发我吗?

My head is spinning, can someone please enlighten me?

推荐答案

SelectableList<int> intList = new SelectableList<int>();
((INotifyPropertyChanged)intList).PropertyChanged += 
    new PropertyChangedEventHandler(intList_Changed);

ObservableCollection 实现INotifyPropertyChanged的实现 ,这意味着您必须先将实例转换为接口,然后才能访问接口的方法,属性和事件.至于为什么这样做,我不知道. 绑定标记扩展 n不会知道"的ObservableCollections或任何其他类型.它检查类型以查看它们是否实现或扩展了特定的接口/基类(INPC,INCC,DependencyObject等),因此不必关心接口是否显式实现.

ObservableCollection implements INotifyPropertyChanged explicitly, which means you have to cast the instance to the interface before you can access the interface's methods, properties and events. As to why this is done, I don't know. The Binding markup extension doesn't "know" ObservableCollections or any other type. It checks types to see if they implement or extend specific interfaces/base classes (INPC, INCC, DependencyObject, etc) and so doesn't care if the interface is implemented explicitly.

这篇关于ObservableCollection PropertyChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆