由于其他工作,好多天又没有对MetaModelEngine进行思考了,这两天又腾出时间可以思考一下了,本篇介绍一下在图形编辑器中对操作如何实现Undo操作。
在图形设计器操作中,每个操作按钮都对应到一个命令,很多情况下我们都应该允许用户执行操作后回滚这些操作,或者回滚后又再次执行。在我做的报表引擎中,我是在每次操作后把设计文件都保留下来,这个在报表设计中是没有问题,但是在毕竟不是很好的设计。接下来要考虑对OpenExpressApp提供建模支持了,所以也需要考虑一下如何让图形设计器更好的支持这种Undo操作。
在公司的一个项目组中内部是使用命令模式,只是在传统命令模式中增加了一个UnExecute方法,这个方法就是用来做Undo操作的。在codeplex上我找到了一类似的轻量级UndoFramework,后期准备就用它了,在这里我就给大家介绍一下。
UndoFramework项目
Codeplex网站地址:http://undo.codeplex.com/
下载地址:http://undo.codeplex.com/releases/view/29440
项目描述:
It's a simple framework to add Undo/Redo functionality to your applications, based on the classical Command design pattern. It supports merging actions, nested transactions, delayed execution (execution on top-level transaction commit) and possible non-linear undo history (where you can have a choice of multiple actions to redo).
The status of the project is Stable (released). I might add more stuff to it later, but right now it fully satisfies my needs. It's implemented in C# 3.0 (Visual Studio 2008) and I can build it for both desktop and Silverlight. The release has both binaries.
现有应用
A good example of where this framework is used is the Live Geometry project (http://livegeometry.codeplex.com). It defines several actions such as AddFigureAction, RemoveFigureAction, MoveAction and SetPropertyAction.
如何使用
我学习这些东西一般都喜欢先看如何使用,因为从使用方式就能看出封装得是否简单易用。
以下是一个控制台的演示程序,代码如下:
04 | namespace MinimalSample |
08 | static void Main( string [] args) |
10 | Console.WriteLine( "Original color" ); |
12 | SetConsoleColor(ConsoleColor.Green); |
13 | Console.WriteLine( "New color" ); |
16 | Console.WriteLine( "Old color again" ); |
18 | using (Transaction.Create(actionManager)) |
20 | SetConsoleColor(ConsoleColor.Red); |
21 | Console.WriteLine( "Still didn't change to Red because of lazy evaluation" ); |
22 | SetConsoleColor(ConsoleColor.Blue); |
24 | Console.WriteLine( "Changed two colors at once" ); |
27 | Console.WriteLine( "Back to original" ); |
30 | Console.WriteLine( "Blue again" ); |
34 | static void SetConsoleColor(ConsoleColor color) |
36 | SetConsoleColorAction action = new SetConsoleColorAction(color); |
37 | actionManager.RecordAction(action); |
40 | static ActionManager actionManager = new ActionManager(); |
43 | class SetConsoleColorAction : AbstractAction |
45 | public SetConsoleColorAction(ConsoleColor newColor) |
51 | ConsoleColor oldColor; |
53 | protected override void ExecuteCore() |
55 | oldColor = Console.ForegroundColor; |
56 | Console.ForegroundColor = color; |
59 | protected override void UnExecuteCore() |
61 | Console.ForegroundColor = oldColor; |
运行后界面如下:
![](https://i-blog.csdnimg.cn/blog_migrate/164dc03872156abe8dfca1f606d2c840.png)
下载代码你会看到,它还自带一个Form的例子,感兴趣可以自己去看看
![](https://i-blog.csdnimg.cn/blog_migrate/d19a238d1a3f66ba4348998d1b58ff6d.png)
Actions
所有操作都从 IAction继承下来,必须实现两个操作:一个是执行操作,一个是反执行操作