Table of Contents

Undo and redo

The namespace ExControls.Providers has two history components: UndoRedoManager keeps the changes that the user can undo and redo, BackwardForwardProvider the places the user can go back and forward to, like a web browser. UndoRedoActionChooser shows the undo or redo history as a list, so several actions can be undone at once.

Commands

A change is an IUndoRedoCommand with a CommandName for the menu and the methods Undo and Redo. The application makes the change itself and only then adds the command to the history; AddCommand doesn't execute it.

public sealed class RenameCommand(Item item, string oldName, string newName) : IUndoRedoCommand
{
    public string CommandName => $"Rename {oldName}";
    public void Undo() => item.Name = oldName;
    public void Redo() => item.Name = newName;
}

var history = new UndoRedoManager { ManagerEnabled = true };

var oldName = item.Name;
item.Name = newName;
history.AddCommand(new RenameCommand(item, oldName, newName));

ManagerEnabled is false by default. Until it is turned on, AddCommand ignores the commands and Undo and Redo throw InvalidOperationException. A new command clears the redo history.

Member Description
Undo(), Redo() Undo or redo one command.
Undo(command), Redo(command) Undo or redo all commands up to the given one, including it.
CanUndo, CanRedo Whether there is something to undo or redo, for example to enable the buttons.
GetUndoText(), GetRedoText() Name of the next command, for menu items like "Undo Rename".
NextUndoCommand, NextRedoCommand The next command without undoing it.
GetUndoHistory(), GetRedoHistory() All commands, the next one first.
Clear() Empties the history, for example after a change that can't be undone.

Record the changes where the user makes them, for example in the handler of a button. A change recorded in an event such as TextChanged would be recorded again when Undo changes the text back.

Handlers

AddCommand(command, handler) adds a command together with an IUndoHandler. The manager then asks the handler to undo and redo the command instead of the command itself, which suits commands that only carry data, such as a snapshot of a document, and one object that knows how to apply them.

Saved state

SetSavedState() marks the current state as saved, IsInSavedState() tells whether the history is back in that state, also after undoing to it. The command that was the newest one when the state was saved is in SavedStateCommand.

void Save()
{
    document.Save(path);
    history.SetSavedState();
    UpdateTitle();
}

void UpdateTitle() => Text = document.Name + (history.IsInSavedState() ? "" : " *");

Events

CommandAdded occurs when a command is added (NewCommand, NewHandler), UndoRedoStateChanged when a command is undone or redone or the history is cleared (NewState is Undo, Redo or Clear). Both are the place to update the buttons, menu items and the title of the window.

Undoing several actions

ToolStripUndoRedoActionChooser is a drop-down for a ToolStripSplitButton. When it opens, the newest action is selected; moving the mouse selects the actions up to the one under the cursor and a click undoes them. The line under the list shows the number of selected actions.

var undoList = new ToolStripUndoRedoActionChooser();
undoList.Chooser.CountText = count => count == 1 ? "Undo 1 action" : $"Undo {count} actions";

undoButton.DropDown = undoList;                    // undoButton is a ToolStripSplitButton
undoButton.ButtonClick += (_, _) => history.Undo();
undoButton.DropDownOpening += (_, _) => undoList.Chooser.SetCommands(history.GetUndoHistory());
undoList.Chooser.CommandChosen += (_, _) => history.Undo(undoList.Chooser.FinalCommand!);

The redo button works the same way with GetRedoHistory and Redo. The drop-down closes itself after a choice.

UndoRedoActionChooser is the list itself, a UserControl that can also be placed on a form: fill it with SetCommands, call OnShown whenever it is shown and handle CommandChosen. FinalCommand is the last chosen action. The library has no texts of its own language, so set CountText for the language of the application.

Both controls implement IThemeable. The drop-down isn't a control of the form, so ExThemer.Apply(form.Controls, theme) doesn't reach it; apply the theme to it directly or in the handler of the tool strip:

foreach (var item in toolStrip.Items.OfType<ToolStripDropDownItem>())
    if (item.DropDown is IThemeable dropDown)
        dropDown.ApplyTheme(theme);

Back and forward

BackwardForwardProvider remembers places in the application, for example the selected node of a tree, and moves between them. A place is an IBackwardForwardCommand with a CommandName and Move, which returns the application to that place.

public sealed class SelectNode(TreeView tree, TreeNode node) : IBackwardForwardCommand
{
    public string CommandName => node.Text;
    public void Move() => tree.SelectedNode = node;
}

var navigation = new BackwardForwardProvider { ManagerEnabled = true };
var moving = false;
tree.AfterSelect += (_, e) =>
{
    if (!moving)
        navigation.AddCommand(new SelectNode(tree, e.Node!));
};

void Back()
{
    moving = true;   // the selection made by Move is not a new place
    try { navigation.Backward(); }
    finally { moving = false; }
}

The added command becomes the CurrentCommand. Backward() and Forward() move one place and call Move of the place they move to, Backward(command) and Forward(command) jump to a place in the history. CanBackward, CanForward, GetBackwardText, GetForwardText, GetBackwardHistory and GetForwardHistory work like their undo counterparts. A place added after going back clears the forward history. ManagerEnabled is false by default here too.

Try it

ExControlsTester shows the history in the menu Okno, Späť a znovu: adding and removing items of a list, the Späť and Znovu split buttons with their drop-downs and the saved state in the title of the window.

API