我们在使用SpreadsheetControl或者RichEditControl的时候可能会需要对此类控件的系统事件做一些定制和干预,比如我们需要在文档保存前判断一下文档内容的大小,或者在文件打开的判断一下内容是否包含某些敏感词等等,该如何操作呢?
这时候我们就需要用到它们各自的CommandService了,话不多说,直接上代码!
SpreadsheetControl:
[C#] 纯文本查看 复制代码
public static class MyCommandHelper
{
public static void SetMyNewCommandFactory(SpreadsheetControl control)
{
ISpreadsheetCommandFactoryService service = (ISpreadsheetCommandFactoryService)control.GetService(typeof(ISpreadsheetCommandFactoryService));
CustomService customService = new CustomService(service);
control.ReplaceService<ISpreadsheetCommandFactoryService>(customService);
customService.Control = control;
}
}
public class CustomService : SpreadsheetCommandFactoryServiceWrapper
{
public CustomService(ISpreadsheetCommandFactoryService service) : base(service) { }
public SpreadsheetControl Control { get; set; }
public override SpreadsheetCommand CreateCommand(SpreadsheetCommandId id)
{
if (id == SpreadsheetCommandId.FileSave)
return new CustomSaveDocumentCommandCommand(Control);
return base.CreateCommand(id);
}
}
public class CustomSaveDocumentCommandCommand : SaveDocumentCommand
{
public CustomSaveDocumentCommandCommand(ISpreadsheetControl control) : base(control) { }
protected override void ExecuteCore()
{
if (Control.ActiveSheet.Name == "test")
MessageBox.Show("表名不合法不让保存!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
base.ExecuteCore();
}
}
//调用:
MyCommandHelper.SetMyNewCommandFactory(spreadsheetControl1);
RichEditControl:
[C#] 纯文本查看 复制代码
public static class MyCommandHelper
{
public static void SetMyNewCommandFactory(RichEditControl control)
{
var myCommandFactory = new CustomRichEditCommandFactoryService(control, control.GetService<IRichEditCommandFactoryService>());
control.ReplaceService<IRichEditCommandFactoryService>(myCommandFactory);
}
}
public class CustomRichEditCommandFactoryService : IRichEditCommandFactoryService
{
readonly IRichEditCommandFactoryService service;
readonly RichEditControl control;
public CustomRichEditCommandFactoryService(RichEditControl control,
IRichEditCommandFactoryService service)
{
this.control = control;
this.service = service;
}
public RichEditCommand CreateCommand(RichEditCommandId id)
{
if (id == RichEditCommandId.FileSave)
return new CustomSaveDocumentCommand(control);
return service.CreateCommand(id);
}
}
public class CustomSaveDocumentCommand : SaveDocumentCommand
{
public CustomSaveDocumentCommand(IRichEditControl control) : base(control) { }
protected override void UpdateUIStateCore(ICommandUIState state)
{
base.UpdateUIStateCore(state);
state.Enabled = Control.Document.Paragraphs.Count < 7;
}
protected override void ExecuteCore()
{
if (Control.Document.Paragraphs.Count > 7)
MessageBox.Show("段落太多不让保存!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
base.ExecuteCore();
}
}
//调用:
MyCommandHelper.SetMyNewCommandFactory(richEditControl1);
大家还可以通过判断它们各自的CommandId来实现不同的功能干预。是不是很简单呢?
|