Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM Light and Undo / Redo?

I am probably mixing up some responsibilities (and maybe even terminology) here, but I can't quite wrap my head around this.

Is there any relationship between the Command Pattern and the Commands found in MVVM Light (and therefore aswell in WPF)? I would really love to implement some kind of undo / redo mechanism but can't quite figure out if there is an "MVVM Light way" of doing it.

And if this is not in relation to MVVM Light, how could I approach commanding with Undo / Redo in "raw" by not working against MVVM Light WPF?

like image 300
Marcus Riemer Avatar asked Feb 26 '23 08:02

Marcus Riemer


2 Answers

The commanding in MVVM Light and WPF in general is a way to encapsulate arbitrary sets of functionality within a single object and interface, and to wire up any number of UI elements to execute that action.

These commands can be incorporated into a command pattern implementation of undo/redo functionality, but you need more.

You can roll your own command stack, which is the route I've taken in my current WPF project (using Prism).

Basically, it is a shift of mindset where every change that a user can make through the UI

  1. is wrapped in a command
  2. has a corresponding undo command
  3. gets pushed to a stack

There are also open-source projects available to help with this, including http://undo.codeplex.com/, which is a side project of Kirill Osenkov, a member of the Visual Studio team.

like image 129
Jay Avatar answered Mar 07 '23 17:03

Jay


I implemented undo / redo for a WPF application and publishing my undo / redo code to http://muf.codeplex.com/.

I considered trying the recommended approach of using the Command pattern to encapsulate the logic. It seems good on paper, but in my case it seemed very challenging to figure out how to put every action into a command that could reliably undo / redo a set of changes. Instead, I took the approach of "monitoring" the underlying model for changes and then storing those changes in the undo stack. This is kind of like the command pattern, but in a "bottom up" approach. The undo actions "fall out" as a result of changing the model.

The actions are gathered by intercepting changes in the setters of the model, storing them into a unit of change with delegates for undoing / redoing the change, and then putting that on a stack of changes. The MUF library includes the logic for managing the stack, creating a unit of change, and more.

Comments and questions are welcome on the codeplex site ( http://muf.codeplex.com/ ). You'll also find complete documentation and sample apps there.

You can also get it via NuGet. Just look for "MUF" or "Monitored Undo Framework". It includes support for Silverlight 4.0, as well as .NET 3.5, 4.0, and WP7.

like image 38
NathanAW Avatar answered Mar 07 '23 16:03

NathanAW