Our company is building a word add-in (document-level add-in) with visual studio 2010, word 2007 and VSTO 3.0 sp1. We found strange behavior regarding changing tables and controls in those changed tables. So we created this simple
POC project to show this issue and to ask for possible workarounds.
We have two classes. PocRibbon class and ThisDocument class.
PrivateSub btnInsertControl_Click(ByVal sender
As System.Object ,
ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs )
Dim document AsThisDocument = Globals .ThisDocument
' Get position point of the control:
AsInteger = document.Application.Selection.Start
' Insert content control:
As Interop.Word.ContentControl = document.ContentControls.Add(WdContentControlType .wdContentControlText, _
controlInterop.Tag = "controlName"
AsPlainTextContentControl = document.Controls.AddPlainTextContentControl(controlInterop, controlInterop.Tag)
MsgBox("Control is Deleted!" )
' In original code, here control's Tools object and event handlers are deleted for this control.
MsgBox("Control is Added!" )
' In original code, here is control's Tools object recreated and handlers readded.
In ribbon this document-level add-in has one button –
btnInsertControl . When user clicks on this button, empty plain text control is inserted into document on current cursor location. This only works correctly if current selection is in main document
part, not in header or footer.
In ThisDocument class we have two simple event handlers that only notify user about events (Document.ContentControlBeforeDelete
and Document.ContentControlAfterAdd ).
Scenario that will display the issue is following:·
Insert table into the document. ·
Place selection into one table cell. ·
Click Insert control button from ribbon (control will be inserted into the cell you have selected, Event
ContentControlAfterAdd is raised
Change table by adding new column into it (Event ContentControlBeforeDelete is raised
It looks like adding new columns into a table means that table will be deleted and replaced with new one that will have all content of old table instead of editing existing one. It means Word will remove
content controls and add new ones too. Problem escalates because, after this happens, event
ContentControlBeforeDeleteis raised but ContentControlAfterAddis not. So this newly added control is “dead” control, because only Interop object is added by Word but not its Tools object and event handlers as well. In original code
ContentControlAfterAddevent handler is used to “revive” readded controls (on Undo/Redo for example) by adding control’s Tools object and old event handlers.
Anyone has an idea how to recognize these events or can propose any workarounds?