ObservableCollection<T> in Winforms and possible alternatives

蓝咒 提交于 2019-11-29 08:39:10

The ObservableCollection class is in the WindowsBase assembly, so you'd need to add WindowsBase to your project references to "access" it.

That being said, I don't think ObservableCollection is going to give you everything you want. Your bound control will get notified when you add or remove items, but there is no automatic property change notification, which is what it sounds like you want.

Regardless of what sort of collection you end up using, I think you're on the right track with INotifyPropertyChanged. Here's a simple example of implementing INotifyPropertyChanged:

class Foo : INotifyPropertyChanged
{
    #region Bar property

    private string _bar;
    public string Bar
    {
        get { return _bar; }
        set
        {
            if (_bar != value)
            {
                _bar = value;

                OnPropertyChanged("Bar");
            }
        }
    }

    #endregion

    protected void OnPropertyChanged(string name)
    {
        var handler = PropertyChanged;

        if (handler != null)
            handler(this, new PropertyChangedEventArgs(name));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Basically, any time a property of your object changes, fire the PropertyChanged event, passing the name of the property that changed.

Finally, all of this may be moot, because you said that you want to change the value of an object's property in response to a change to a control bound to that property. The usual Windows Forms data binding infrastructure can make that happen without the help of INotifyPropertyChanged or any other interface. You only need to implement INotifyPropertyChanged if you need to notify a bound control of changes to your object's properties from elsewhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!