I'm trying to access all Rich-Text-Content-Controls of an existing .docx Document (Office Open XML).
I've found a way to get all Content Controls of a Document by looping over a specified range:
var contentControls = new List<ContentControl>();
Range rangeStory;
foreach (Range range in wordDocument.StoryRanges)
{
rangeStory = range;
do
{
try
{
contentControls.AddRange(rangeStory.ContentControls.Cast<ContentControl>());
}
catch (COMException) { }
rangeStory = rangeStory.NextStoryRange;
}
while (rangeStory != null);
}
But I can't find a way to cast these ContentControls (assembly: Microsoft.Office.Interop.Word
) to RichTextContentControls (assembly: Microsoft.Office.Tools.Word
).
RichTextContentControl richTextContentControl = contentControl as RichTextContentControl;
throws Exception
I want to do this casting, because I need to subscribe to RichTextContentControl's entering and exiting events.
richTextContentControl.Entering += (sender, args) => {/*..*/ };
richTextContentControl.Exiting += (sender, args) => {/*..*/ };
Found it! There is a very easy way to access any kind of Content Controls via Vsto:
foreach (var result in thisDocument.Controls.OfType<RichTextContentControl>())
{
result.Entering += (sender, args) =>
{
MediatorContext.Current.Send(new CurrentKomponenteChangedRequest(result.ID, State.Entering));
};
result.Exiting += (sender, args) =>
{
MediatorContext.Current.Send(new CurrentKomponenteChangedRequest(result.ID, State.Exiting));
};
}