2013-10-21 32 views
1

如何在WPF中使用MVVM模式集合的屬性實現IsDirty機制?如何在使用WPF的MVVM模式中集合的屬性上實現IsDirty?

IsDirty是一個標誌,用於指示viewmodel中的數據是否已更改並用於保存操作。

如何傳播IsDirty?

+0

我強烈建議你閱讀[這篇文章](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+0

'IsDirty'被視爲'ViewModel的另一個屬性';當需要保存時,檢查對象是否髒污並進行必要的工作。你究竟想傳播什麼? –

+3

我更喜歡使用髒標誌的版本計數器。任何變化都會增加計數器。存儲上次保存操作的計數器。通過比較來計算'IsDirty'。 – CodesInChaos

回答

1

您可以實現沿着這些路線自定義集合...

public class MyCollection<T>:ObservableCollection<T>, INotifyPropertyChanged 
    { 
     // implementation goes here... 
     // 
     private bool _isDirty; 
     public bool IsDirty 
     { 
      [DebuggerStepThrough] 
      get { return _isDirty; } 
      [DebuggerStepThrough] 
      set 
      { 
       if (value != _isDirty) 
       { 
        _isDirty = value; 
        OnPropertyChanged("IsDirty"); 
       } 
      } 
     } 
     #region INotifyPropertyChanged Implementation 
     public event PropertyChangedEventHandler PropertyChanged; 
     protected virtual void OnPropertyChanged(string name) 
     { 
      var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null); 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(name)); 
      } 
     } 
     #endregion 
    } 

,並宣佈你的收藏這樣的...

MyCollection<string> SomeStrings = new MyCollection<string>(); 
SomeStrings.Add("hello world"); 
SomeStrings.IsDirty = true; 

此方法可讓你享受的ObservableCollection的好處,同時允許你添加一個感興趣的屬性。如果您的Vm不使用ObservableCollection,則可以使用相同的模式繼承T的List。

相關問題