How to: Replace Standard DXRichEdit Command with a Custom Command

  • 2 minutes to read

The following example describes how to replace the built-in command with a custom one using the service substitution technique.

  1. Create a target command descendant and override its required members.

    In this example, the CustomSaveDocumentCommand class is a SaveDocumentCommand descendant. It overrides the ExecuteCore method to display a message after a document has been saved.

    public class CustomSaveDocumentCommand:SaveDocumentCommand{
        public CustomSaveDocumentCommand(IRichEditControl control)
            : base(control)
        protected override void ExecuteCore()
              MessageBox.Show("Custom SaveDocument command was executed");
  2. Implement the IRichEditCommandFactoryService descendant. Create a CreateCommand method to generate a new custom command object used to replace the built-in command.

    public class CustomRichEditCommandFactoryService : IRichEditCommandFactoryService
        readonly IRichEditCommandFactoryService service;
        readonly RichEditControl control;
        public CustomRichEditCommandFactoryService(RichEditControl control,
            IRichEditCommandFactoryService service) {
            Guard.ArgumentNotNull(control, "control");
            Guard.ArgumentNotNull(service, "service");
            this.control = control;
            this.service = service;
        public RichEditCommand CreateCommand(RichEditCommandId id) {
            if(id == RichEditCommandId.FileSave)
                return new CustomSaveDocumentCommand(control);
            return service.CreateCommand(id);
  3. In the RichEditControl.Loaded event handler, create a new IRichEditCommandFactoryService descendant instance and use the RichEditControl.ReplaceService<T> method to substitute the default service with the newly created service.

    void richEditControl1_Loaded(object sender, RoutedEventArgs e) {
    void ReplaceRichEditCommandFactoryService(RichEditControl control)
        IRichEditCommandFactoryService service = control.GetService<IRichEditCommandFactoryService>();
        control.ReplaceService<IRichEditCommandFactoryService>(new CustomRichEditCommandFactoryService(control, service));