Reputation: 2503
How to implement IsDirty mechanism on properties that are collections in MVVM pattern with WPF?
IsDirty is a flag that indicates if the data in the viewmodel has changed and it is used for the save operation.
How to propagate IsDirty ?
Upvotes: 1
Views: 2366
Reputation: 8802
You can implement a custom collection along these lines...
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
}
And declare your collections like this...
MyCollection<string> SomeStrings = new MyCollection<string>();
SomeStrings.Add("hello world");
SomeStrings.IsDirty = true;
This approach lets you enjoy the benefits of ObservableCollection and simultaneously allows you to append a property of interest. If your Vm's do not use ObservableCollection, you can inherit from List of T using the same pattern.
Upvotes: 1