Share via


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.

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 Visual Studio Settings.

Prerequisites

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](bb398242\(v=vs.100\).md).
  • Microsoft Office Word 2007 or Word 2010.

link to video 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

  1. In the Word document that is hosted in the Visual Studio designer, on the Ribbon, click the Insert tab.

  2. In the Tables group, click Table, and insert a table with 2 columns and 3 rows.

  3. Type text in the first column so that it resembles the following column:

    Employee Name

    Hire Date

    Title

  4. In the second column of the table, click in the first row (next to Employee Name).

  5. On the Ribbon, click 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.

  6. In the Controls group, click the Text button PlainTextContentControl to add a PlainTextContentControl to the first cell.

  7. In the second column of the table, click in the second row (next to Hire Date).

  8. In the Controls group, click the Date Picker button DatePickerContentControl to add a DatePickerContentControl to the second cell.

  9. In the second column of the table, click in the third row (next to Title).

  10. In the Controls group, click the Drop-Down List button DropDownListContentControl 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

  1. On the Project menu, click Add New Item.

    The Add New Item dialog box appears.

  2. In the Templates pane, select XML File.

  3. Name the file employees.xml, and then click Add.

    The employees.xml file opens in the Code Editor.

  4. 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>
    
  5. In Solution Explorer, click employees.xml.

  6. 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

  1. On the Project menu, click Add New Item.

    The Add New Item dialog box appears.

  2. In the Templates pane, select XML Schema.

  3. Name the schema employees.xsd and click Add.

    The schema designer opens.

  4. In Solution Explorer, right-click employees.xsd, and then click View Code.

  5. 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>
    
  6. 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

  1. Activate EmployeeControls.docx in the designer.

  2. On the Ribbon, click the Developer tab.

  3. In the XML group, click Schema.

  4. In the Templates and Add-ins dialog box, click the XML Schema tab, and then click Add Schema.

  5. Browse to the employees.xsd schema you created earlier, which is located in your project directory, and click Open.

  6. Click OK in the Schema Settings dialog box.

  7. Click OK to close the Templates and Add-ins dialog box.

    The XML Structure task pane opens.

  8. 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

  1. In Solution Explorer, right-click ThisDocument.cs or ThisDocument.vb, and then click View Code.

  2. 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'";
    
  3. 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;
    }
    
  4. 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, missing);
                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

  1. Press F5 to run the project.

  2. 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

  3. Click in the cell to the right of the Employee Name cell and type a different name.

  4. Click in the cell to the right of the Hire Date cell and select a different date in the date picker.

  5. Click in the cell to the right of the Title cell and select a new item from the drop-down list.

  6. Save and close the document.

  7. In Windows Explorer, open the \bin\Debug folder under the location of your project.

  8. Right-click EmployeeControls.docx and then click Rename.

  9. 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.

  10. Double-click the EmployeeControls.docx.zip file.

  11. Double-click the customXml folder.

  12. Right-click item2.xml and then click Open.

    This file contains the custom XML part that you added to the document.

  13. Verify that the name, hireDate, and title elements contain the new values that you entered into the content controls in the document.

  14. Close the item2.xml file.

Next Steps

You can learn more about how to use content controls from these topics:

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

Content Controls

Host Items and Host Controls Overview

Programmatic Limitations of Host Items and Host Controls

Adding Controls to Office Documents at Run Time

Helper Methods for Host Controls