Two-way binding of Xml data to the WPF TreeView


I am attempting to rewrite my ForestPad application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible.

In general, what is the best way to two-way databind the WPF TreeView to an Xml document?

A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this:

<?xml version="1.0" encoding="utf-8"?>
    created="5/14/2004 1:05:10 AM"
    updated="5/14/2004 1:07:41 AM">
    name="A forest node"
    created="01/01/2003 1:00:00 AM"
    updated="5/14/2004 1:06:15 AM">
    <![CDATA[A forest node
        This is the text of the forest node.]]>
        name="A tree node"
        created="5/14/2004 1:05:38 AM"
        updated="5/14/2004 1:06:11 AM">
        <![CDATA[A tree node
            This is the text of the tree node.]]>
            name="A branch node"
            created="5/14/2004 1:06:00 AM"
            updated="5/14/2004 1:06:24 AM">
            <![CDATA[A branch node
                This is the text of the branch node.]]></data>
                name="A leaf node"
                created="5/14/2004 1:06:26 AM"
                updated="5/14/2004 1:06:38 AM">
                <![CDATA[A leaf node
                    This is the text of the leaf node.]]>
3/28/2011 8:47:02 PM

Accepted Answer

Well, it would be easier if your element hierarchy was more like...

<node type="forest">
    <node type="tree">

...rather than your current schema.

As-is, you'll need 4 HierarchicalDataTemplates, one for each hierarchical element including the root, and one DataTemplate for leaf elements:

        ItemsSource="{Binding XPath=forest}">
            Text="a forestpad" />
        ItemsSource="{Binding XPath=tree}">
            Text="{Binding XPath=data}" />
        ItemsSource="{Binding XPath=branch}">
            Text="{Binding XPath=data}" />
        ItemsSource="{Binding XPath=leaf}">
            Text="{Binding XPath=data}" />
            Text="{Binding XPath=data}" />

        XPath="forestPad" Source="D:\fp.xml">

You can instead set the Source of the XmlDataProvider programmatically:

dp = this.FindResource( "dataxml" ) as XmlDataProvider;
dp.Source = new Uri( @"D:\fp.xml" );

Also, re-saving your edits is as easy as this:

dp.Document.Save( dp.Source.LocalPath );

The TreeView itself needs a Name and an ItemsSource bonded to the XmlDataProvider:

    ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}">

I this example, I did TwoWay binding with TextBoxes on each node, but when it comes to editing just one node at a time in a separate, single TextBox or other control, you would be binding it to the currently selected item of the TreeView. You would also change the above TextBoxes to TextBlocks, as clicking in the TextBox does not actually select the corresponding TreeViewItem.

    DataContext="{Binding ElementName=treeview, Path=SelectedItem}"
    Text="{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}"/>

The reason you must use two Bindings is that you cannot use Path and XPath together.


Timothy Lee Russell asked about saving CDATA to the data elements. First, a little on InnerXml and InnerText.

Behind the scenes, XmlDataProvider is using an XmlDocument, with it's tree of XmlNodes. When a string such as "stuff" is assigned to the InnerXml property of an XmlNode, then those tags are really tags. No escaping is done when getting or setting InnerXml, and it is parsed as XML.

However, if it is instead assigned to the InnerText property, the angle brackets will be escaped with entities &lt; and &gt;. The reverse happens when the value is retreived. Entities (like &lt;) are resolved back into characters (like <).

Therefore, if the strings we store in the data elements contain XML, entities have been escaped, and we need to undo that simply by retrieving InnerText before adding a CDATA section as the node's child...

XmlDocument doc = dp.Document;

XmlNodeList nodes = doc.SelectNodes( "//data" );

foreach ( XmlNode node in nodes ) {
    string data = node.InnerText;
    node.InnerText = "";
    XmlCDataSection cdata = doc.CreateCDataSection( data );
    node.AppendChild( cdata );

doc.Save( dp.Source.LocalPath );

If the node already has a CDATA section and the value has not been changed in any way, then it still has a CDATA section and we essentially replace it with the same. However, through our binding, if we change the value of the data elements contents, it replaces the CDATA in favor of an escaped string. Then we have to fix them.

10/10/2008 2:18:33 PM

We had a similar issue. You may find reading this article helpful. We used the ViewModel pattern described and it simplified everything.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow