2011-12-12 54 views
19

我有一個簡單的類與一個字符串屬性和List屬性,我有INofityPropertyChanged事件實現,但當我做一個.Add添加到字符串列表這個事件沒有命中,所以我的轉換器顯示在ListView沒有被擊中。我猜屬性改變沒有命中一個添加到列表....我怎麼能實現這個方式來獲得該屬性更改事件命中?List <string> INotifyPropertyChanged事件

我是否需要使用其他類型的集合?

感謝您的幫助!

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

回答

32

您應該使用ObservableCollection<string>,而不是List<string>。在你的情況下,我只能使_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"); 
    } 

    ... 

} 
+0

這是錢!謝謝! – theDoke

+0

**爲什麼**應該使用'ObservableCollection'? – C4u

+0

@ C4u它可以用於WPF中的數據綁定(MVVM模式) – bniwredyc

2

您的列表不會自動觸發NotifyPropertyChanged事件。

WPF控制該露出ItemsSource屬性被設計成結合到一個ObservableCollection<T>,其更新時自動項目被添加或移除。

7

使WPF的列表綁定工作最簡單的方法是使用實​​現INotifyCollectionChanged的集合。這裏要做的一件簡單的事情就是用ObservableCollection替換或修改你的列表。

如果使用ObservableCollection,那麼無論何時修改列表,它都會引發CollectionChanged事件 - 一個會告訴WPF綁定更新的事件。請注意,如果換出實際的集合對象,您將需要爲實際的集合屬性引發propertychanged事件。

+0

如果我不想因性能原因而使用它,該怎麼辦? – Brandon

相關問題