【问题标题】:How to implement IsDirty on properties that are collections in MVVM pattern with WPF?如何使用 WPF 在 MVVM 模式中的集合属性上实现 IsDirty?
【发布时间】:2013-10-21 20:35:35
【问题描述】:

如何使用 WPF 对 MVVM 模式中的集合属性实现 IsDirty 机制?

IsDirty 是一个标志,指示视图模型中的数据是否已更改,并用于保存操作。

如何传播 IsDirty ?

【问题讨论】:

  • 我强烈建议你阅读this article
  • IsDirty 被视为ViewModel 上的另一个属性;当需要保存时,检查对象是否脏并做必要的工作。你到底想传播什么?
  • 我更喜欢版本计数器而不是脏标志。增加任何变化的计数器。存储上次保存操作的计数器。通过比较它们来计算IsDirty

标签: c# wpf mvvm observablecollection inotifypropertychanged


【解决方案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,您可以使用相同的模式从 List of T 继承。

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多