我正在创建一个Word加载项,允许用户选择Word文档中的各种文本,然后单击功能区上的一个按钮,该按钮将使用内容控件(富文本)包装该文本。最终,这些内容控件将映射到XML。
到目前为止,代码是这样的:
for i in list:
for element in i:
if is_date(element):
list2.append(element)
所有这一切都很好,它第一次点击按钮时有效。但是,如果有多个标题' (在这种情况下)需要添加,并且用户第二次按下按钮,它会抛出错误:
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";
}
}
很清楚为什么会抱怨,但我无法想出允许多次点击按钮生成同一类型的多个内容控件(富文本内容控件)的正确方法同名("标题"例如)。
请有人指出我正确的方向。
答案 0 :(得分:0)
好的,这就是我最终的表现:
private void addTitle_Click(object sender, RibbonControlEventArgs e)
{
AddRichTextControlAtSelection();
}
int count = 0;
private void AddRichTextControlAtSelection()
{
word.Document currentDocument = Globals.ThisAddIn.Application.ActiveDocument;
Document extendedDocument = Globals.Factory.GetVstoObject(currentDocument);
if (currentDocument.ContentControls.Count > 0)
{
currentDocument.ActiveWindow.Selection.Range.HighlightColorIndex = word.WdColorIndex.wdYellow;
currentDocument.ActiveWindow.Selection.Range.Select();
richTextControls = new List<RichTextContentControl>();
foreach (word.ContentControl nativeControl in currentDocument.ContentControls)
{
if (nativeControl.Type == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlRichText)
{
count++;
RichTextContentControl tempControl = extendedDocument.Controls.AddRichTextContentControl("VSTORichTextControl" + count.ToString());
richTextControls.Add(tempControl);
tempControl.Title = "Title";
tempControl.Tag = "title";
break;
}
}
}
else
{
RichTextContentControl VSTORichTextControl;
VSTORichTextControl = extendedDocument.Controls.AddRichTextContentControl("VSTORichTextControl");
VSTORichTextControl.PlaceholderText = "Enter the DM title";
VSTORichTextControl.Title = "Title";
VSTORichTextControl.Tag = "title";
}
}