我正在创建一个 Word 加载项,它允许用户在 Word 文档中选择各种文本,然后单击功能区上的按钮,该按钮将使用内容控件(富文本)包装该文本。最终,这些内容控件将被映射到 XML。
到目前为止的代码是这样的:
public partial class Ribbon1
{
private RichTextContentControl titleRichTextControl;
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void addTitle_Click(object sender, RibbonControlEventArgs e)
{
AddRichTextControlAtSelection();
}
private void AddRichTextControlAtSelection()
{
word.Document currentDocument = Globals.ThisAddIn.Application.ActiveDocument;
currentDocument.ActiveWindow.Selection.Range.Select();
Document extendedDocument = Globals.Factory.GetVstoObject(currentDocument);
titleRichTextControl = extendedDocument.Controls.AddRichTextContentControl("titleRichTextControl");
titleRichTextControl.PlaceholderText = "Enter the title";
titleRichTextControl.Title = "Title";
titleRichTextControl.Tag = "title";
}
}
这一切都很好,它在第一次单击按钮时起作用。但是,如果有多个“标题”(在这种情况下)需要添加,并且用户再次按下按钮,则会引发错误:
The control cannot be added because a control with the name titleRichTextControl already exists in the Controls collection.
很清楚它为什么会抱怨,但我想不出正确的方法来允许多次单击按钮以生成多个相同类型(富文本内容控件)和相同名称(例如“标题”)的内容控件)。
谁能指出我正确的方向。