C# 如何检测 BindingList<T> 中项目属性的更改?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/655158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect changes to item properties in the BindingList<T>?
提问by Tomas Pajonk
I have a custom class Foo with properties A and B. I want to display it in a databinding control.
我有一个带有属性 A 和 B 的自定义类 Foo。我想在数据绑定控件中显示它。
I have created a class Foos : BindingList<Foo>
.
我创建了一个类Foos : BindingList<Foo>
。
In order to update some internal properties of the Foos class I need to be notified of property changes (I can handle insertions, removals etc.) on the items in the list. How would you implement that functionality ?
为了更新 Foos 类的一些内部属性,我需要收到列表中项目的属性更改(我可以处理插入、删除等)的通知。您将如何实现该功能?
Should I inherit Foo from some object in the framework that supports that ? I think I could create events that notify me if changes, but is that the way it should be done ? Or is there some pattern in the framework, that would help me ?
我应该从支持它的框架中的某个对象继承 Foo 吗?我想我可以创建事件来通知我是否有变化,但应该这样做吗?或者框架中有一些模式可以帮助我吗?
采纳答案by Juliet
Foo should implement the INotifyPropertyChanged
and INotifyPropertyChanging
interfaces.
Foo 应该实现INotifyPropertyChanged
和INotifyPropertyChanging
接口。
public void Foo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private int _someValue;
public int SomeValue
{
get { return _someValue; }
set { _someValue = value; NotifyPropertyChanged("SomeValue"); }
}
}
The BindingList
should hook onto your event handler automatically, and your GUI should now update whenever you set your class invokes the PropertyChanged
event handler.
本BindingList
应自动钩住你的事件处理程序,只要你设置你的类调用你的GUI现在应该更新PropertyChanged
事件处理程序。
[Edit to add:] Additionally, the BindingList
class expose two eventswhich notify you when the collection has been added to or modified:
[编辑添加:]此外,BindingList
该类公开了两个事件,当集合被添加或修改时通知你:
public void DoSomething()
{
BindingList<Foo> foos = getBindingList();
foos.ListChanged += HandleFooChanged;
}
void HandleFooChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
}