25

我有一个带有字符串属性和 List 属性的简单类,并且实现了 INofityPropertyChanged 事件,但是当我执行 .Add 到字符串 List 时,此事件不会被命中,因此要在 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

4 回答 4

47

您应该使用ObservableCollection<string>代替List<string>,因为与 不同ListObservableCollection将在其内容更改时通知家属。

在你的情况下,我会_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");
    }

    ...

}
于 2011-12-12T05:09:42.643 回答
10

使 WPF 的列表绑定工作的最简单方法是使用实​​现INotifyCollectionChanged. 在这里要做的一件简单的事情是用ObservableCollection.

如果您使用ObservableCollection,那么每当您修改列表时,它都会引发 CollectionChanged 事件 - 该事件将告诉 WPF 绑定进行更新。请注意,如果您换出实际的集合对象,您将需要为实际的集合属性引发 propertychanged 事件。

于 2011-12-12T05:04:20.220 回答
4

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

公开ItemsSource属性的 WPF 控件旨在绑定到,当添加或删除项目时,它将自动ObservableCollection<T>更新

于 2011-12-12T05:04:17.153 回答
3

你应该看看ObservableCollection

于 2011-12-12T05:04:22.630 回答