Shomron
Shomron

Reputation: 451

Customize Undo Redo of a RichTextBox

Is there a way to set a Richtextbox that doesn't merge text undo units inside it's undo stack. the default behavior is, when you write text ( all in the same paragraph), the whole text you type belong to the same undo unit. What I want is to have a undo unit per word. I tried this but it didn't work.

--> before you type a text:

myRichTextBox.BeginChange();

--> you just typed a space:

myRichTextBox.EndChange();
myRichTextBox.LockCurrentUndoUnit();
myRichTextBox.BeginChange();

but when I run the app, and after I type some text, the behavior of the undo command (ctrl+z) is still the same.

Upvotes: 1

Views: 1838

Answers (1)

Ramin
Ramin

Reputation: 2133

Override OnPreviewKeyDown(KeyEventArgs e) method of the RichTextBox, and then add sth like this:

if (e.Key==Key.Space)
{
   BeginChange();
   //set logical direction to be backward
   CaretPosition = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Backward);
   CaretPosition.InsertTextInRun(" "); // Insert space
   CaretPosition = CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
   e.Handled = true;
   EndChange();
}

You can insert other chars, like "{", "}", ... to have a same behavior.

This works for me.

Upvotes: 1

Related Questions