Skip to main content

Commands in Rich Text Editor for WPF

  • 6 minutes to read

The Rich Text Editor for WPF ships with a comprehensive set of commands that allows you to perform basic operations (format and edit text, create lists, add headers and footers, work with tables, etc.). All commands implemented in the Rich Text Editor control inherit from the Command object. Refer to a following topic for a full list of built-in commands: Command UI in Rich Text Editor for WPF

Create and Execute Commands in Code

You can create a new object of the required Command descendant to create a new command. You can also call the RichEditControl.CreateCommand method and pass the required RichEditCommandId enumeration member as a parameter to create a command.

The Command class has the following methods used to execute the command action:

Command.Execute
The main method. Cannot be utilized when the command is disabled (use the Command.CanExecute() to determine whether the command can be executed).
Command.ForceExecute
Use this method if the command is disabled or if you require to execute the command with a parameter (for example, navigate to a page by its number). The ICommandUIState.EditValue property allows you to specify a command parameter.

The following code calls the RichEditControl.CreateCommand method to create commands based on CapitalizeEachWordTextCase, ToggleFontBold, ChangeFontBackColor, and PrintPreview commands. Each command is executed by the ForceExecute method call. The Command.CreateDefaultCommandUIState() method returns the command UI state.

All commands are executed an once on a button click.

static void buttonCustomAction_ItemClick_Commands(object sender, ItemClickEventArgs e) {

    RichEditControl richEdit = e.Item.Tag as RichEditControl;
    richEdit.SelectAll();

    RichEditCommand capCommand = richEdit.CreateCommand(RichEditCommandId.CapitalizeEachWordTextCase);
    capCommand.ForceExecute(capCommand.CreateDefaultCommandUIState());

    RichEditCommand boldCommand = richEdit.CreateCommand(RichEditCommandId.ToggleFontBold);
    boldCommand.ForceExecute(boldCommand.CreateDefaultCommandUIState());

    RichEditCommand changeFontColorCommand = richEdit.CreateCommand(RichEditCommandId.ChangeFontBackColor);
    DevExpress.Utils.Commands.ICommandUIState state = changeFontColorCommand.CreateDefaultCommandUIState();
    state.EditValue = Color.Yellow;
    changeFontColorCommand.ForceExecute(state);

    RichEditCommand previewCommand = richEdit.CreateCommand(RichEditCommandId.PrintPreview);
    previewCommand.ForceExecute(previewCommand.CreateDefaultCommandUIState());

    richEdit.DeselectAll();
}

You can bind a command to any UI element. Refer to the following article for more information: How to: Customize Context Menus for the Rich Text Editor

Best Practices

Take into account the following when you work with commands:

  • The Command UI executes commands that can throw unhandled exceptions if a problem occurs. To prevent application failure, subscribe to the RichEditControl.UnhandledException event and set the RichEditUnhandledExceptionEventArgs.Handled property to true.
  • You should always create a new instance of a command before execution, otherwise you may experience undesired effects and unhandled exceptions.
  • We do not recommend that you execute the disabled command. This may lead to unexpected results.

Customize Built-In Commands

To change the actions performed when the built-in command is executed, use the service substitution technique. Create the IRichEditCommandFactoryService descendant which generates custom commands and use the RichEditControl.ReplaceService<T> method (or the GetService -> RemoveService -> AddService method sequence) to replace default service with a newly created service.

Refer to the following article for more information: How to: Replace Standard DXRichEdit Command with a Custom Command

Change Shortcut Keys

The commands in Rich Text Editor ship with assigned keyboard shortcuts. You can use the RichEditControl.RemoveShortcutKey and the RichEditControl.AssignShortcutKeyToCommand methods to modify shortcut keys assigned to commands. Refer to the following article for a full list of available shortcuts: Keyboard Shortcuts

The following example removes the Ctrl+O shortcut and assigns the Alt+Y shortcut to the CreateFieldCommand to insert a field::

using System.Windows.Forms;
//...
public MainWindow()
{
    InitializeComponent();
    richEditControl.Loaded += RichEditControl_DocumentLoaded;
}

private void RichEditControl_DocumentLoaded(object sender, EventArgs e)
{
    richEditControl.RemoveShortcutKey(Keys.O, Keys.Control, true);
    richEditControl1.AssignShortcutKeyToCommand(Keys.Y, Keys.Alt, RichEditCommandId.CreateField, RichEditViewType.PrintLayout);
}

Disable Built-In Commands

Restrict Operations

Use the RichEditControl.BehaviorOptions and DocumentOptions.DocumentCapabilities properties to disable the required functionality in the Rich Text Editor. As a result, the corresponding commands are also disabled.

The table below lists options and the operations they manage:

Functionality Option
Create new documents DXRichEditBehaviorOptions.CreateNew
Open documents DXRichEditBehaviorOptions.Open
Save documents DXRichEditBehaviorOptions.Save
DXRichEditBehaviorOptions.SaveAs
Printing DXRichEditBehaviorOptions.Printing
Encryption DXRichEditBehaviorOptions.Encrypt
Clipboard operations DXRichEditBehaviorOptions.Copy
DXRichEditBehaviorOptions.Cut
DXRichEditBehaviorOptions.Paste
Undo operations DXRichEditDocumentCapabilitiesOptions.Undo
Page layout (page breaks, margins, columns, orientation, line numbering) DXRichEditDocumentCapabilitiesOptions.Sections
Tables DXRichEditDocumentCapabilitiesOptions.Tables
Headers and footers DXRichEditDocumentCapabilitiesOptions.HeadersFooters
Track Changes DXRichEditDocumentCapabilitiesOptions.TrackChanges
Comments DXRichEditDocumentCapabilitiesOptions.Comments
Footnotes and endnotes DXRichEditDocumentCapabilitiesOptions.EndNotes
DXRichEditDocumentCapabilitiesOptions.FootNotes
Fields (including mail merge) DXRichEditDocumentCapabilitiesOptions.Fields
Text formatting DXRichEditDocumentCapabilitiesOptions.CharacterFormatting
DXRichEditDocumentCapabilitiesOptions.CharacterStyle
DXRichEditDocumentCapabilitiesOptions.ParagraphFormatting
DXRichEditDocumentCapabilitiesOptions.ParagraphStyle
Lists DXRichEditDocumentCapabilitiesOptions.NumberingOptions

The code sample below hides all printing and page layout commands and disables zooming commands in a Ribbon UI:

<dxr:RichEditControl x:Name="richEditControl1"
                     CommandBarStyle="Ribbon">
    <dxr:RichEditControl.BehaviorOptions>
        <dxr:DXRichEditBehaviorOptions Printing="Hidden"
                                       Zooming="Hidden"/>
    </dxr:RichEditControl.BehaviorOptions>
    <dxr:RichEditControl.DocumentCapabilitiesOptions>
        <dxr:DXRichEditDocumentCapabilitiesOptions Sections="Disabled"/>
    </dxr:RichEditControl.DocumentCapabilitiesOptions>
</dxr:RichEditControl>

Disable or Hide a Command with the Specified Condition

You can disable or hide a command when meeting the specified criteria. Create a custom command and override its UpdateCommandUIState method. Change the state depending on the required condition. Set the ICommandUIState.Enabled property to false to disable the command; set the ICommandUIState.Visible property to false to hide the command.

The code sample below creates a custom Replace command and disables it if the document is protected:

public class CustomReplaceCommand : ReplaceCommand {
    public CustomReplaceCommand(IRichEditControl control) : base(control)
    {
    }
    public override void UpdateUIState(ICommandUIState state)
    {
        base.UpdateUIState(state);
        if (this.Control.Document.IsDocumentProtected)
            state.Enabled = false;
    }
}

public class CustomRichEditCommandFactoryService : IRichEditCommandFactoryService {
    readonly IRichEditCommandFactoryService service;
    readonly RichEditControl control;

    public CustomRichEditCommandFactoryService(RichEditControl control, IRichEditCommandFactoryService service)
    {
        DevExpress.Utils.Guard.ArgumentNotNull(control, "control");
        DevExpress.Utils.Guard.ArgumentNotNull(service, "service");
        this.control = control;
        this.service = service;
    }

    public RichEditCommand CreateCommand(RichEditCommandId id)
    {
        if (id == RichEditCommandId.Replace)
            return new CustomReplaceCommand(control);
        return service.CreateCommand(id);
    }
}