Skip to main content
A newer version of this page is available. .

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.

    View Example

    public class CustomSaveDocumentCommand:SaveDocumentCommand{
        public CustomSaveDocumentCommand(IRichEditControl control)
            : base(control)
        {
        }
        protected override void ExecuteCore()
        {
              base.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.

    View Example

    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.

    View Example

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