您可以实现几个接口来帮助进行更改跟踪和撤消:INotifyPropertyChanged 和 IEditableObject。这两个接口都允许对象很好地使用数据绑定。
public class Person : INotifyPropertyChanged, IEditableObject
{
private bool isDirty;
public bool IsDirty
{
get { return isDirty; }
}
private string firstname = string.Empty;
public string Firstname
{
get { return firstname; }
set
{
if (firstname == value) return;
firstname = value;
NotifyPropertyChanged("Firstname");
}
}
private string lastname = string.Empty;
public string Lastname
{
get { return lastname; }
set
{
if (lastname == value) return;
lastname = value;
NotifyPropertyChanged("Lastname");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
isDirty = true;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private bool inTrans;
private Person copy;
public void BeginEdit()
{
if (!inTrans)
{
if (copy == null)
copy = new Person();
copy.isDirty = isDirty;
copy.Firstname = Firstname;
copy.Lastname = Lastname;
inTrans = true;
isDirty = false;
}
}
public void CancelEdit()
{
if (inTrans)
{
isDirty = copy.isDirty;
Firstname = copy.Firstname;
Lastname = copy.Lastname;
inTrans = false;
}
}
public void EndEdit()
{
if (inTrans)
{
copy = null;
inTrans = false;
}
}
}