列出 INotifyPropertyChanged事件
我有一个带有字符串属性和List属性的简单类,我实现了INofityPropertyChanged事件,但当我对字符串List执行.Add时,此事件未被命中,因此我的ListView中显示的Converter未被命中。 我猜测属性已更改未被添加到列表中….如何实现此方法以获取该属性更改事件命中???
我需要使用其他类型的collections吗?!
谢谢你的帮助!
namespace SVNQuickOpen.Configuration { public class DatabaseRecord : INotifyPropertyChanged { public DatabaseRecord() { IncludeFolders = new List(); } #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 _includeFolders; public List IncludeFolders { get { return _includeFolders; } set { this._includeFolders = value; Notify("IncludeFolders"); } } } }
您应该使用ObservableCollection
而不是List
。 在你的情况下,我将_includeFolders
只读 – 你可以随时使用该集合的一个实例。
public class DatabaseRecord : INotifyPropertyChanged { private readonly ObservableCollection _includeFolders; public ObservableCollection IncludeFolders { get { return _includeFolders; } } public DatabaseRecord() { _includeFolders = new ObservableCollection (); _includeFolders.CollectionChanged += IncludeFolders_CollectionChanged; } private void IncludeFolders_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Notify("IncludeFolders"); } ... }
使WPF的列表绑定工作的最简单方法是使用实现INotifyCollectionChanged
的集合。 这里要做的一件简单的事情是使用ObservableCollection
替换或修改您的列表。
如果使用ObservableCollection
,那么无论何时修改列表,它都会引发CollectionChanged事件 – 这个事件将告诉WPF绑定更新。 请注意,如果换出实际的集合对象,则需要为实际集合属性引发propertychanged事件。
您的列表不会自动为您激活NotifyPropertyChanged事件。
公开ItemsSource
属性的WPF控件被设计为绑定到ObservableCollection
, 它将在添加或删除项时自动更新。
你应该看看ObservableCollection