简体   繁体   English

如何检测 BindingList 中项目属性的更改<t> ?</t>

[英]How can I detect changes to item properties in the BindingList<T>?

I have a custom class Foo with properties A and B. I want to display it in a databinding control.我有一个具有属性 A 和 B 的自定义 class Foo。我想在数据绑定控件中显示它。

I have created a class Foos: BindingList<Foo> .我创建了一个 class 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.为了更新 Foos class 的一些内部属性,我需要通知列表中项目的属性更改(我可以处理插入、删除等)。 How would you implement that functionality?您将如何实现该功能?

Should I inherit Foo from some object in the framework that supports that?我应该从支持它的框架中的一些 object 继承 Foo 吗? 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 should implement the INotifyPropertyChanged and INotifyPropertyChanging interfaces. Foo 应该实现INotifyPropertyChangedINotifyPropertyChanging接口。

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 现在应该在您设置 class 调用PropertyChanged事件处理程序时更新。

[Edit to add:] Additionally, the BindingList class expose two events which notify you when the collection has been added to or modified: [编辑添加:] 此外, BindingList class 公开两个事件,当集合被添加或修改时通知您:

public void DoSomething()
{
    BindingList<Foo> foos = getBindingList();
    foos.ListChanged += HandleFooChanged;
}

void HandleFooChanged(object sender, ListChangedEventArgs e)
{
    MessageBox.Show(e.ListChangedType.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM