How can I detect changes to item properties in the BindingList?

后端 未结 1 687
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-19 05:16

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

I have created a class Foos : BindingList .

相关标签:
1条回答
  • 2021-02-19 05:41

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

    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.

    [Edit to add:] Additionally, the BindingList class expose 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());
    }
    
    0 讨论(0)
提交回复
热议问题