VSTO Word 加载项:内容控件嵌套



我正在为我实习的公司构建一个MS-Word加载项。

我已经创建了一个包含大量SplitButtonsButtons的新功能区。 现在我想做的是,当您单击内容控件将添加到单词文档中的按钮之一时。 这适用于普通内容控件。这些内容控件具有绑定到 XML 文件中的元素的"运动/篮球/球员/名称"等标记。

private void addSimpleContentControl(String tag, String placeholder)
{
    try
    {
        contentControlPlain = Globals.ThisAddIn.Application.ActiveDocument.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText);
        contentControlPlain.Tag = tag;
        contentControlPlain.SetPlaceholderText(null, null, placeholder);
    }
    catch (COMException) { }    
} 

现在让我们谈谈我的问题。 我的一些元素可能会存在不止一次。因此,我要创建的是一个包含多个纯内容控件的丰富内容控件。

所以我有一个SplitButton"球员",上面有"姓名"、"球衣号码"、"位置"等按钮,..... 当单击其中一个底层按钮时,我首先检查是否已经存在具有特定名称的富文本控件。 如果没有,我会制作一个并向其添加一个普通内容控件。

丰富内容控件 ->纯文本控件 ->结束 内容控件

到目前为止一切顺利,一切都很好,但是从我想将另一个普通内容控件添加到丰富内容控件的那一刻起,就会弹出:

"纯文本控件不能插入到其他控件或 XML 元素周围"

下面是将纯内容控件添加到丰富内容控件的代码。

private void addContentControlToRich(String tag, String placeholder,String title) 
{
    Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
    foreach (Microsoft.Office.Interop.Word.ContentControl cc in doc.ContentControls)
    {
        if (cc.Title == title && cc.Type == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlRichText)
        {
            try
            {
                Microsoft.Office.Interop.Word.Range rng = cc.Range;
                object oRng = rng;
                contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
                contentControlPlain.Tag = tag;
                contentControlPlain.SetPlaceholderText(null, null, placeholder);
                contentControlPlain.LockContentControl = true;
                break;
            }
            catch (COMException) { }
        }
    }
}

而不是

contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);

contentControlPlain = richTextControl.Range.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);

在使用上面的代码之前,请使用下面的代码

Application.Selection.Start = lastControlinRichTextControl.Range.End+1;

并设置 'oRng = 应用程序.选择.范围

根据消息,您的代码正在尝试将纯文本控件包装在富文本控件(即现有的纯文本控件)中的所有内容周围。 修复您的范围对象,以便它不会这样做,例如将其折叠到富文本控件中的一个点。

最新更新