Walkthrough: Binding Content Controls to Custom XML Parts
This walkthrough demonstrates how to bind content controls in a document-level customization for Word to XML data that is stored in the document.
Applies to: The information in this topic applies to document-level projects for Word 2007 and Word 2010. For more information, see Features Available by Office Application and Project Type.
Word enables you to store XML data, named custom XML parts, in a document. You can control the display of this data by binding content controls to elements in a custom XML part. The example document in this walkthrough displays employee information that is stored in a custom XML part. When you open the document, the content controls display the values of the XML elements. Any changes that you make to the text in the content controls are saved in the custom XML part.
This walkthrough illustrates the following tasks:
Adding content controls to the Word document in a document-level project at design time.
Creating an XML data file and an XML schema that defines the elements to bind to the content controls.
Attaching the XML schema to the document at design time.
Adding the contents of the XML file to a custom XML part in the document at run time.
Binding the content controls to elements in the custom XML part.
Binding a DropDownListContentControl to a set of values that are defined in the XML schema.
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.
You need the following components to complete this walkthrough:
An edition of Visual Studio 2010 that includes the Microsoft Office developer tools. For more information, see Configuring a Computer to Develop Office Solutions.
Microsoft Office Word 2007 or Word 2010.
For a video version of this topic, see Video How to: Binding Content Controls to Custom XML Parts.
Create a Word document that you will use in the walkthrough.
To create a new Word document project
Create a Word document project with the name EmployeeControls. Create a new document for the solution. For more information, see How to: Create Office Projects in Visual Studio.
Visual Studio opens the new Word document in the designer and adds the EmployeeControls project to Solution Explorer.
Create a table that contains three different types of content controls where the user can view or edit information about an employee.
To add content controls to the document
In the Word document that is hosted in the Visual Studio designer, on the Ribbon, click the Insert tab.
In the Tables group, click Table, and insert a table with 2 columns and 3 rows.
Type text in the first column so that it resembles the following column:
In the second column of the table, click in the first row (next to Employee Name).
On the Ribbon, click the Developer tab.
If the Developer tab is not visible, you must first show it. For more information, see How to: Show the Developer Tab on the Ribbon.
In the Controls group, click the Text button to add a PlainTextContentControl to the first cell.
In the second column of the table, click in the second row (next to Hire Date).
In the Controls group, click the Date Picker button to add a DatePickerContentControl to the second cell.
In the second column of the table, click in the third row (next to Title).
In the Controls group, click the Drop-Down List button to add a DropDownListContentControl to the last cell.
That is the entire user interface for this project. If you run the project now, you can type text in the first row and select a date in the second row. The next step is to attach the data that you want to display to the document in an XML file.
Typically, you will obtain XML data to store in a custom XML part from an external source, such as a file or a database. In this walkthrough, you create an XML file that contains the employee data, marked by elements that you will bind to the content controls in the document. To make the data available at runtime, embed the XML file as a resource in the customization assembly.
To create the data file
On the Project menu, click Add New Item.
The Add New Item dialog box appears.
In the Templates pane, select XML File.
Name the file employees.xml, and then click Add.
The employees.xml file opens in the Code Editor.
Replace the contents of the employees.xml file with the following text.
<?xml version="1.0" encoding="utf-8" ?> <employees xmlns="http://schemas.microsoft.com/vsto/samples"> <employee> <name>Karina Leal</name> <hireDate>1999-04-01</hireDate> <title>Manager</title> </employee> </employees>
In Solution Explorer, click employees.xml.
In the Properties window, select the Build Action property, and then change the value to Embedded Resource.
This step embeds the XML file as a resource in the assembly when you build the project. This enables you to access the contents of the XML file at run time.
If you want to bind a content control to a single element in a custom XML part, you do not have to use an XML schema. However, to bind the DropDownListContentControl to a set of values, you must create an XML schema that validates the XML data file that you created earlier. The XML schema defines the possible values for the title element. You will bind the DropDownListContentControl to this element later in this walkthrough.
To create an XML schema
On the Project menu, click Add New Item.
The Add New Item dialog box appears.
In the Templates pane, select XML Schema.
Name the schema employees.xsd and click Add.
The schema designer opens.
In Solution Explorer, right-click employees.xsd, and then click View Code.
Replace the contents of the employees.xsd file with the following schema.
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns="http://schemas.microsoft.com/vsto/samples" targetNamespace="http://schemas.microsoft.com/vsto/samples" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="employees" type="EmployeesType"></xs:element> <xs:complexType name="EmployeesType"> <xs:all> <xs:element name="employee" type="EmployeeType"/> </xs:all> </xs:complexType> <xs:complexType name="EmployeeType"> <xs:sequence> <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1"/> <xs:element name="hireDate" type="xs:date" minOccurs="1" maxOccurs="1"/> <xs:element name="title" type="TitleType" minOccurs="1" maxOccurs="1"/> </xs:sequence> </xs:complexType> <xs:simpleType name="TitleType"> <xs:restriction base="xs:string"> <xs:enumeration value ="Engineer"/> <xs:enumeration value ="Designer"/> <xs:enumeration value ="Manager"/> </xs:restriction> </xs:simpleType> </xs:schema>
On the File menu, click Save All to save your changes to the employees.xml and the employees.xsd files.
You must attach the XML schema to the document to bind the DropDownListContentControl to the valid values of the title element.
To attach the XML schema to the document
Activate EmployeeControls.docx in the designer.
On the Ribbon, click the Developer tab.
In the XML group, click Schema.
In the Templates and Add-ins dialog box, click the XML Schema tab, and then click Add Schema.
Browse to the employees.xsd schema you created earlier, which is located in your project directory, and click Open.
Click OK in the Schema Settings dialog box.
Click OK to close the Templates and Add-ins dialog box.
The XML Structure task pane opens.
Close the XML Structure task pane.
Before you can bind the content controls to the elements in the XML file, you must add the contents of the XML file to a new custom XML part in the document.
To add a custom XML part to the document
In Solution Explorer, right-click ThisDocument.cs or ThisDocument.vb, and then click View Code.
Add the following declarations to the ThisDocument class. This code declares several objects that you will use to add a custom XML part to the document.
Add the following method to the ThisDocument class. This method gets the contents of the XML data file that is embedded as a resource in the assembly, and returns the contents as an XML string.
Private Function GetXmlFromResource() As String Dim asm As System.Reflection.Assembly = _ System.Reflection.Assembly.GetExecutingAssembly() Dim stream1 As System.IO.Stream = asm.GetManifestResourceStream( _ "EmployeeControls.employees.xml") Using resourceReader As System.IO.StreamReader = _ New System.IO.StreamReader(stream1) If resourceReader IsNot Nothing Then Return resourceReader.ReadToEnd() End If End Using Return Nothing End Function
Add the following method to the ThisDocument class. The AddCustomXmlPart method creates a new custom XML part that contains an XML string that is passed to the method.
To ensure that the custom XML part is only created once, the method creates the custom XML part only if a custom XML part with a matching GUID does not already exist in the document. The first time this method is called, it saves the value of the Id property to the employeeXMLPartID string. The value of the employeeXMLPartID string is persisted in the document because it was declared by using the CachedAttribute attribute.
Private Sub AddCustomXmlPart(ByVal xmlData As String) If xmlData IsNot Nothing Then employeeXMLPart = Me.CustomXMLParts.SelectByID(employeeXMLPartID) If (employeeXMLPart Is Nothing) Then employeeXMLPart = Me.CustomXMLParts.Add(xmlData) employeeXMLPart.NamespaceManager.AddNamespace("ns", _ "http://schemas.microsoft.com/vsto/samples") employeeXMLPartID = employeeXMLPart.Id End If End If End Sub
Bind each content control to an element in the custom XML part by using the XMLMapping property of each content control.
To bind the content controls to elements in the custom XML part
Add the following method to the ThisDocument class. This method binds each content control to an element in the custom XML part and sets the date display format of the DatePickerContentControl.
Private Sub BindControlsToCustomXmlPart() Dim xPathName As String = "ns:employees/ns:employee/ns:name" Me.PlainTextContentControl1.XMLMapping.SetMapping(xPathName, _ prefix, employeeXMLPart) Dim xPathDate As String = "ns:employees/ns:employee/ns:hireDate" Me.DatePickerContentControl1.DateDisplayFormat = "MMMM d, yyyy" Me.DatePickerContentControl1.XMLMapping.SetMapping(xPathDate, _ prefix, employeeXMLPart) Dim xPathTitle As String = "ns:employees/ns:employee/ns:title" Me.DropDownListContentControl1.XMLMapping.SetMapping(xPathTitle, _ prefix, employeeXMLPart) End Sub
Create the custom XML part and bind the custom controls to the data when the document is opened.
To run your code when the document is opened
Add the following code to the ThisDocument_Startup method of the ThisDocument class. This code gets the XML string from the employees.xml file, adds the XML string to a new custom XML part in the document, and binds the content controls to elements in the custom XML part.
When you open the document, the content controls display data from the elements in the custom XML part. You can click the DropDownListContentControl to select one of three valid values for the title element, which are defined in the employees.xsd file. If you edit the data in any of the content controls, the new values are saved in the custom XML part in the document.
To test the content controls
Press F5 to run the project.
Verify that the table in the document resembles the following table. Each of the strings in the second column is obtained from an element in the custom XML part in the document.
April 1, 1999
Click in the cell to the right of the Employee Name cell and type a different name.
Click in the cell to the right of the Hire Date cell and select a different date in the date picker.
Click in the cell to the right of the Title cell and select a new item from the drop-down list.
Save and close the document.
In Windows Explorer, open the \bin\Debug folder under the location of your project.
Right-click EmployeeControls.docx and then click Rename.
Name the file EmployeeControls.docx.zip.
The EmployeeControls.docx document is saved in the Open XML Format. By renaming this document with the .zip file name extension, you can examine the contents of the document. For more information about Open XML, see the technical article Introducing the Office (2007) Open XML File Formats.
Double-click the EmployeeControls.docx.zip file.
Double-click the customXml folder.
Right-click item2.xml and then click Open.
This file contains the custom XML part that you added to the document.
Verify that the name, hireDate, and title elements contain the new values that you entered into the content controls in the document.
Close the item2.xml file.
You can learn more about how to use content controls from these topics:
Use all the available content controls to create a template. For more information, see Walkthrough: Creating a Template By Using Content Controls.
Modify the data in the custom XML parts while the document is closed. The next time the user opens the document, the content controls that are bound to the XML elements will display the new data. For more information, see How to: Add Custom XML Parts to Documents Without Starting Microsoft Office.
Use content controls to protect parts of a document. For more information, see How to: Protect Parts of Documents by Using Content Controls.