如何检测BindingList< T>中项目属性的更改? [英] How can I detect changes to item properties in the BindingList<T>?

查看:425
本文介绍了如何检测BindingList< T>中项目属性的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类Foo的属性A和B.我想显示在一个数据绑定控件。

I have a custom class Foo with properties A and B. I want to display it in a databinding control.

我创建了一个类 Foos:BindingList< Foo>

为了更新Foos类的一些内部属性,我需要通知属性更改我可以处理插入,删除等)列表中的项目。您将如何实现该功能?

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 ?

我应该从框架中的某个对象继承Foo吗?我想我可以创建事件通知我,如果改变,但是,它应该如何做?或者在框架中有一些模式,这会帮助我吗?

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应该实现 INotifyPropertyChanged INotifyPropertyChanging 接口。

Foo should implement the INotifyPropertyChanged and INotifyPropertyChanging interfaces.

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"); }
    }
}

BindingList应该自动挂钩到你的事件处理程序,现在你的GUI应该在你设置类调用PropertyChanged事件处理程序时更新。

The BindingList should hook onto your event handler automagically, and your GUI should now update whever you set your class invokes the PropertyChanged event handler.

此外,BindingList类发布了两个事件,当收集已添加或修改时通知您:

Additionally, the BindingList class exposted two events which notify you when the collection has been added to or modified:

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

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

这篇关于如何检测BindingList&lt; T&gt;中项目属性的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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