Control Persistence

VSTO bookmarks that are added to a document programmatically are not persisted in the document in the way you might expect. After the document is saved and closed, the bookmark is stored in the document, but it does not retain its VSTO capabilities. The bookmark is stored as an Interop bookmark rather than a VSTO bookmark. Any of its data binding capabilities or events are not available the next time you open the document. You must write code to add the bookmark to the Controls collection again.

You do this by adding the VSTO bookmark to the document (using AddBookmark), but this time you pass the Interop bookmark as the location you want the bookmark to appear rather than a specific range. This also means that you can create a VSTO bookmark for an existing Interop bookmark. Listing 6.10 demonstrates how to reconnect an Interop bookmark with VSTO capabilities.

Listing 6.10. Reconnecting a bookmark with VSTO capabilities

Dim InteropBookmark As Word.Bookmark = Bookmarks.Add( _ "Bookmark2", Me.Paragraphs(1).Range)

Dim VSTOBookmark As Microsoft.Office.Tools.Word. _

Bookmark = Me.Controls.AddBookmark(InteropBookmark, _ InteropBookmark.Name)

VSTOBookmark.Text = "Sample text"

In this case, you can use the same name as an existing bookmark because you are replacing it with a new VSTO bookmark that doesn't already exist in the Controls collection. You'll learn about this, and other bookmark enhancements, later in this chapter.

0 0

Post a comment