BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Base Classes - TextBoxBase - Undo and Redo

The sixtieth part of the Windows Presentation Foundation Fundamentals tutorial continues the examination of the TextBoxBase class, a base class for text input controls. This article considers the in-built undo and redo capabilities.

Determining if Undo and Redo are Available

You may need to detect when the undo and redo features are available for a text box. For example, you might want to provide an undo button that is enabled only when there is a change to be undone. In these cases you can read the CanUndo and CanRedo properties. Both are Boolean properties that are true when the matching method will change the control's content and false otherwise.

To demonstrate, we'll link the two properties to the read-only CheckBoxes. We'll change the IsChecked property, when the text changes or one of the buttons is used, to show the current state of the properties. NB: In a real WPF application, this could be achieved with data binding, which we will examine later in the tutorial.

Replace the Undo_Click and Redo_Click methods with the code below:

private void Undo_Click(object sender, RoutedEventArgs e)
{
    MyTextBox.Undo();
    ShowFlags();
}

private void Redo_Click(object sender, RoutedEventArgs e)
{
    MyTextBox.Redo();
    ShowFlags();
}

private void MyTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    ShowFlags();
}

private void ShowFlags()
{
    CanUndoCheckBox.IsChecked = MyTextBox.CanUndo;
    CanRedoCheckBox.IsChecked = MyTextBox.CanRedo;
}

IsUndoEnabled Flag

The last property that we'll consider is IsUndoEnabled. This is another Boolean property. Its value specifies whether the undo and redo features are permitted to be used. By default, it is set to true to allow the user to rectify errors. If you wish to disable undo and redo you can set it to false. NB: If you set the value to false, then back to true, the "undo stack" is cleared, preventing any undo or redo operation, except after new text changes.

The following modified Click method for the final CheckBox changes the property to match the checked status of the control. Update the code and try enabling and disabling undo to see the effect.

private void IsUndoEnabledCheckBox_Click(object sender, RoutedEventArgs e)
{
    MyTextBox.IsUndoEnabled = ((CheckBox)sender).IsChecked.Value;
    ShowFlags();
}
9 May 2014