在另一个ContentControl之后插入ContentControl

时间:2010-04-29 08:34:19

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

在我们的VSTO Word 2010 Addin中,我们尝试在给定的其他ContentControl之后插入RichTextControl。我们试过这个:

    public ContentControl AddContentControl(WdContentControlType type, int position)
    {
        Paragraph paragraphBefore = null;
        if (position == 0)
        {
            if (WordDocument.Paragraphs.Count == 0)
            {
                WordDocument.Paragraphs.Add();
            }
            paragraphBefore = WordDocument.Paragraphs.First;
        }
        else
        {
            paragraphBefore = Controls.ElementAt(position - 1).Range.Paragraphs.Last;
        }

        object start = paragraphBefore.Range.End;
        object end = paragraphBefore.Range.End + 1;

        paragraphBefore.Range.InsertParagraphAfter();

        Range rangeToUse = WordDocument.Range(ref start, ref end);

        ContentControl newControl = _ContentControl = _WordDocument.ContentControls.Add(type, rangeToInsert);

        Controls.Insert(position, newControl);

        OnNewContentControl(newControl, position);

        return newControl.ContentControl;
    }

工作正常,除非我们想要插入的控件在结尾处有一个空段落。如果是这种情况,则将新的ContentControl插入到最后一个控件中。

我们怎样才能避免这种情况?

1 个答案:

答案 0 :(得分:5)

答案有点迟,但这就是我处理这个案子所做的事情:

我认为这基本上就是你所做的,但是我插入了一个段落,然后转到Paragraph单元。似乎在我的案例中工作。

Globals.ThisDocument.Paragraphs.First.Range.Select();

var cc = Globals.ThisDocument.Controls.AddRichTextContentControl(Guid.NewGuid().ToString());

var newRange = cc.Range;
object count = 1;
newRange.Move(Unit: Word.WdUnits.wdParagraph, Count: ref count);

Globals.ThisDocument.Paragraphs.Add();
newRange.Move(Unit: Word.WdUnits.wdParagraph, Count: ref count);

var cc2 = Globals.ThisDocument.Controls.AddRichTextContentControl(newRange, Guid.NewGuid().ToString());