C#中的List<string> INotifyPropertyChanged事件

29
我有一个简单的类,其中包含一个字符串属性和一个列表属性,我实现了INotifyPropertyChanged事件,但是当我向字符串列表添加元素时,此事件并未触发,导致我的转换器无法在ListView中显示。 我猜测当向列表添加元素时,该属性未被标记为更改……如何实现以使该属性更改事件被触发?
我需要使用其他类型的集合吗?
谢谢任何帮助!
namespace SVNQuickOpen.Configuration
{
    public class DatabaseRecord : INotifyPropertyChanged 
    {
        public DatabaseRecord()
        {
            IncludeFolders = new List<string>();
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void Notify(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion

        private string _name;

        public string Name
        {
            get { return _name; }

            set
            {
                this._name = value;
                Notify("Name");
            }
        }

        private List<string> _includeFolders;

        public List<string> IncludeFolders
        {
            get { return _includeFolders; }

            set
            {
                this._includeFolders = value;
                Notify("IncludeFolders");
            }
        }
    }
}
4个回答

54

你应该使用 ObservableCollection<string> 而不是 List<string>,因为与 List 不同,ObservableCollection 在其内容更改时会通知依赖项。

在你的情况下,我会将 _includeFolders 设为只读 - 你总是可以使用一个集合实例进行操作。

public class DatabaseRecord : INotifyPropertyChanged 
{
    private readonly ObservableCollection<string> _includeFolders;

    public ObservableCollection<string> IncludeFolders
    {
        get { return _includeFolders; }
    }

    public DatabaseRecord()
    {
        _includeFolders = new ObservableCollection<string>();
        _includeFolders.CollectionChanged += IncludeFolders_CollectionChanged;
    }

    private void IncludeFolders_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Notify("IncludeFolders");
    }

    ...

}

2
为什么应该使用 ObservableCollection - C4d
@C4u 它可以用于 WPF 中的数据绑定(MVVM 模式)。 - bniwredyc

11

让 WPF 的列表绑定最简单的方法是使用实现了 INotifyCollectionChanged 接口的集合。一个简单的方法是用一个 ObservableCollection 来替换或者适应你的列表。

如果你使用了 ObservableCollection,那么每当你修改列表时,它就会触发 CollectionChanged 事件 - 一个告诉 WPF 绑定更新的事件。请注意,如果你交换了实际的集合对象,你需要为实际的集合属性引发 propertychanged 事件。


4

你的List不会自动触发NotifyPropertyChanged事件。

暴露ItemsSource属性的WPF控件被设计为绑定到ObservableCollection<T>,当添加或删除项时,它自动更新。


3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接