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 2013 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.
Note
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 Customizing Development Settings in Visual Studio.
Prerequisites
You need the following components to complete this walkthrough:
An edition of Visual Studio 2013 that includes the Microsoft Office developer tools. For more information, see Configuring a Computer to Develop Office Solutions.
Word 2013 or Word 2010.
For a video version of this topic, see Video How to: Binding Content Controls to Custom XML Parts.
Creating a New Word Document Project
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.
Adding Content Controls to the Document
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, choose the Insert tab.
In the Tables group, choose Table, and insert a table with 2 columns and 3 rows.
Type text in the first column so that it resembles the following column:
Employee Name
Hire Date
Title
In the second column of the table, choose the first row (next to Employee Name).
On the Ribbon, choose the Developer tab.
Note
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, choose the Text button to add a PlainTextContentControl to the first cell.
In the second column of the table, choose the second row (next to Hire Date).
In the Controls group, choose the Date Picker button to add a DatePickerContentControl to the second cell.
In the second column of the table, choose the third row (next to Title).
In the Controls group, choose 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.
Creating the XML Data 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, choose Add New Item.
The Add New Item dialog box appears.
In the Templates pane, select XML File.
Name the file employees.xml, and then choose the Add button.
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="https://schemas.microsoft.com/vsto/samples"> <employee> <name>Karina Leal</name> <hireDate>1999-04-01</hireDate> <title>Manager</title> </employee> </employees>
In Solution Explorer, choose the employees.xml file.
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.
Creating an XML Schema
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, choose Add New Item.
The Add New Item dialog box appears.
In the Templates pane, select XML Schema.
Name the schema employees.xsd and choose the Add button.
The schema designer opens.
In Solution Explorer, open the shortcut menu for employees.xsd, and then choose View Code.
Replace the contents of the employees.xsd file with the following schema.
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns="https://schemas.microsoft.com/vsto/samples" targetNamespace="https://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.
Attaching the XML Schema to the Document
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 (Word 2013)
Activate EmployeeControls.docx in the designer.
On the Ribbon, choose the Developer tab, and then choose the Add-Ins button.
In the Templates and Add-ins dialog box, choose the XML Schema tab, and then choose the Add Schema button.
Browse to the employees.xsd schema you created earlier, which is located in your project directory, and then choose the Open button.
Choose the OK button in the Schema Settings dialog box.
Choose the OK button to close the Templates and Add-ins dialog box.
To attach the XML schema to the document (Word 2010)
Activate EmployeeControls.docx in the designer.
On the Ribbon, choose the Developer tab.
In the XML group, choose the Schema button.
In the Templates and Add-ins dialog box, choose the XML Schema tab, and then choose the Add Schema button.
Browse to the employees.xsd schema that you created earlier, which is located in your project directory, and choose the Open button.
Choose the OK button in the Schema Settings dialog box.
Choose the OK button to close the Templates and Add-ins dialog box.
The XML Structure task pane opens.
Close the XML Structure task pane.
Adding a Custom XML Part to the Document
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, open the shortcut menu for ThisDocument.cs or ThisDocument.vb, and then choose 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.
<Cached()> _ Public employeeXMLPartID As String = String.Empty Private employeeXMLPart As Office.CustomXMLPart Private Const prefix As String = "xmlns:ns='https://schemas.microsoft.com/vsto/samples'"
[CachedAttribute()] public string employeeXMLPartID = string.Empty; private Office.CustomXMLPart employeeXMLPart; private const string prefix = "xmlns:ns='https://schemas.microsoft.com/vsto/samples'";
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
private string GetXmlFromResource() { System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream stream1 = asm.GetManifestResourceStream( "EmployeeControls.employees.xml"); using (System.IO.StreamReader resourceReader = new System.IO.StreamReader(stream1)) { if (resourceReader != null) { return resourceReader.ReadToEnd(); } } return null; }
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", _ "https://schemas.microsoft.com/vsto/samples") employeeXMLPartID = employeeXMLPart.Id End If End If End Sub
private void AddCustomXmlPart(string xmlData) { if (xmlData != null) { employeeXMLPart = this.CustomXMLParts.SelectByID(employeeXMLPartID); if (employeeXMLPart == null) { employeeXMLPart = this.CustomXMLParts.Add(xmlData); employeeXMLPart.NamespaceManager.AddNamespace("ns", @"https://schemas.microsoft.com/vsto/samples"); employeeXMLPartID = employeeXMLPart.Id; } } }
Binding the Content Controls to Elements in the Custom XML Part
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
private void BindControlsToCustomXmlPart() { string xPathName = "ns:employees/ns:employee/ns:name"; this.plainTextContentControl1.XMLMapping.SetMapping(xPathName, prefix, employeeXMLPart); string xPathDate = "ns:employees/ns:employee/ns:hireDate"; this.datePickerContentControl1.DateDisplayFormat = "MMMM d, yyyy"; this.datePickerContentControl1.XMLMapping.SetMapping(xPathDate, prefix, employeeXMLPart); string xPathTitle = "ns:employees/ns:employee/ns:title"; this.dropDownListContentControl1.XMLMapping.SetMapping(xPathTitle, prefix, employeeXMLPart); }
Running Your Code When the Document is Opened
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.
Dim xmlData As String = GetXmlFromResource() If xmlData IsNot Nothing Then AddCustomXmlPart(xmlData) BindControlsToCustomXmlPart() End If
string xmlData = GetXmlFromResource(); if (xmlData != null) { AddCustomXmlPart(xmlData); BindControlsToCustomXmlPart(); }
Testing the Project
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.
Employee Name
Karina Leal
Hire Date
April 1, 1999
Title
Manager
Choose the cell to the right of the Employee Name cell and type a different name.
Choose the cell to the right of the Hire Date cell and select a different date in the date picker.
Choose 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 File Explorer, open the \bin\Debug folder under the location of your project.
Open the shortcut menu for EmployeeControls.docx and then choose 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.
Open the EmployeeControls.docx.zip file.
Open the customXml folder.
Open the shortcut menu for item2.xml and then choose 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.
Next Steps
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.
Use content controls to protect parts of a document. For more information, see How to: Protect Parts of Documents by Using Content Controls.
See Also
Tasks
How to: Add Content Controls to Word Documents
How to: Protect Parts of Documents by Using Content Controls
Concepts
Automating Word by Using Extended Objects
Host Items and Host Controls Overview