这是我用于我的项目的解决方案。事实证明,该解决方案运行良好。
系统正在使用撤消事件对象,其中每个撤消事件都知道如何撤消和重做自身。
interface IUndoEvent
{
void Undo();
void Redo();
}
我能够通过仅实现 2 个撤消事件来构建系统:一个用于属性更改;另一个用于更改属性。一个用于集合更改。
这个想法是这些事件通过直接修改模型来实现撤消/重做。
class PropertyChangeUndoEvent : IUndoEvent
{
private ModelBase _target;
private string _propertyName;
private object _oldValue;
private object _newValue;
public PropertyChangeUndoEvent(ModelBase target, string propertyName, object oldValue, object newValue)
{
_target = target;
_propertyName = propertyName;
_oldValue = oldValue;
_newValue = newValue;
}
public void Undo()
{
SetValue(_oldValue);
}
public void Redo()
{
SetValue(_newValue);
}
private void SetValue(object value)
{
// Set Value on the _target using reflection (_propertyName)
}
}
ViewModel 通过调用 ViewModelBase 函数负责创建撤消事件:
class MyViewModel : ViewModelBase
{
public string Name
{
get { return _model.Name; }
// The SetValue will create a undo event, and push it to the UndoManager
set { SetValue(_model, "Name", value); }
}
}
最后,还有一个UndoManager(项目单例),用于存储撤消堆栈和重做堆栈。