[英]How to implement IsDirty on properties that are collections in MVVM pattern with WPF?
如何使用WPF在MVVM模式中的集合属性上实现IsDirty机制?
IsDirty是一个标志,指示视图模型中的数据是否已更改,并将其用于保存操作。
如何传播IsDirty?
您可以按照以下方式实现自定义集合...
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的列表继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.