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

时间:2012-04-16 06:46:13

标签: c# ms-word vsto ribbonx word-contentcontrol

我正在为我正在实习的公司建立一个MS-Word插件。

我已经创建了一个包含大量SplitButtonsButtons的新功能区。  现在我想要做的是当你点击其中一个内容控件将添加到单词doc的按钮时。  这适用于Plain Content Controls。这些内容控件的标签类似于“sport / basketball / player / name”,它绑定到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) { }    
} 

现在让我们谈谈我的问题。  我的一些元素可能存在超过一次。所以我想创建的是一个Rich Content控件,它包含多个Plain内容控件。

所以我有一个SplitButton“玩家”按钮,如“名字”,“球衣号码”,“位置”,......  单击其中一个基础按钮时,我首先检查是否已存在具有特定名称的富文本控件。  如果不是我制作一个并添加一个单一的Plain内容控件。

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

到目前为止一切顺利,这一切都很顺利,但从我想要添加另一个普通内容控件到富内容控件的那一刻起,这就出现了:

  

“无法在其他控件或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) { }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

而不是

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 = Application.Selection.Range

相关问题