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

How to: Customize Built-in Command Using Service Substitution

  • 3 minutes to read

Use the service substitution technique to customize the built-in command. 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.

The following code implements the IRichEditCommandFactoryService descendant which generates customized SaveDocumentCommand and SaveDocumentAsCommand commands. The command descendants override the ExecuteCore methods to display a message after a document has been saved.

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.FileSaveAs) {
            return new CustomSaveDocumentAsCommand(control);
        }
        if(id == RichEditCommandId.FileSave) {
            return new CustomSaveDocumentCommand(control);
        }
        return service.CreateCommand(id);
    }
}

public class CustomSaveDocumentCommand : SaveDocumentCommand
{
    public CustomSaveDocumentCommand(IRichEditControl richEdit) : base(richEdit) { }

    protected override void ExecuteCore()
    {
        base.ExecuteCore();
        if(!(this.Control as RichEditControl).Modified)
        {
            MessageBox.Show("Document is saved successfully");
        }
    }
}


public class CustomSaveDocumentAsCommand : SaveDocumentAsCommand
{
    public CustomSaveDocumentAsCommand(IRichEditControl richEdit) : base(richEdit)
    { }

    protected override void ExecuteCore()
    {
        (this.Control as RichEditControl).Modified = true;
        base.ExecuteCore();
        if(!(this.Control as RichEditControl).Modified)
        {
            MessageBox.Show("Document is saved successfully");
        }
    }
}

The following code replaces the IRichEditCommandFactoryService service with its customized descendant.

richEditControl.Text = "A message box is displayed after saving a document using the 'Save' or 'Save As' button click since custom commands.";
var myCommandFactory = new CustomRichEditCommandFactoryService(richEditControl, richEditControl.GetService<IRichEditCommandFactoryService>());
richEditControl.ReplaceService<IRichEditCommandFactoryService>(myCommandFactory);