ChrisAn's Blog Please read my disclaimer.

simplegeek

a.k.a. Chris Anderson

Hierarchical Binding

Today I spent some solid time working on the book (9 pages, wahoo!) and worked on a bunch of data binding topics. While it didn't make the book, I really liked this sample I wrote up for showing hierarchical binding.

I started out with a chunk of XML:

      <Media xmlns="">
        <Book Author="John" Title="Fish are my friends" />
        <Book Author="Dave" Title="Fish are my enemies" />
        <Book Author="Jane" Title="Fish are my food" />
        <CD Artist="Jane" Title="Fish sign good" />
        <DVD Director="John" Title="Fish: The movie">
          <Actor>Jane</Actor>
          <Actor>Dave</Actor>
        </DVD>
      </Media>

What I wanted to do was data bind it into a TreeView that would show the structure of the XML... so effectively I wanted:

<Grid 
    xmlns="http://schemas.microsoft.com/winfx/avalon/2005" 
    xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">
  <Grid.Resources>
    <XmlDataProvider x:Key="dataSource">
      ... xml ...
    </XmlDataProvider>
  </Grid.Resources>
  <TreeView 
      ItemsSource="{Binding Source={StaticResource dataSource}}" />
</Grid>

Part of the data binding support in WinFX is native support for hierarchical binding. Basically if you have some data that has hierarchy, and a control that has native hierarchy support, you can wire the two together without a lot of fanfare. The trick is the HierarchicalDataTemplate, which lets you specify how to walk the object graph to produce the hierarchy. What's even better, that because of the automatic look of data templates based on types, you can make this extrememly simple:

        <HierarchicalDataTemplate 
            DataType='{x:Type sx:XmlNode}' 
            ItemsSource='{Binding Path=ChildNodes}'>
                
            <TextBlock Text='{Binding Path=Name}' />
        </HierarchicalDataTemplate>

That's it. With that data template as the ItemTemplate for your TreeView, you will get a complete dump of the template. The content of the HierarchicalDataTemplate is the display tree for the item, and the ItemsSource property controls where the template will get the next level of the hierarchy. Since ChildNodes returns something that is an XmlNode, the template automatically recurses. Pretty cool, huh?

With a little fancier template, you can get something like this:

XAML Source

01/02/2006 2:33 PM | #Programming Avalon #WinFX

Content © 2003 Chris Anderson | Subscribe to my RSS feed.

Powered by BlogX