Share via


Avalon Simple Tree View, Part 4 (now with XML binding!)

There was a question in Avalon newsgroup that mentioned my TreeView sample.

The question: can one bind XML data in a HierachialDataTemplate?

Short answer: yes. Here's how.

First, we need to define an XMLDataSource (yup, just like the ObjectDataSource from the first sample). We put the XML data inside this node.

<XmlDataSource x:Key="ExpenseDataSource" XPath="Expenses">
<Expenses xmlns="">
<Person Name="Mike" Department="Legal">
<Expense ExpenseReason="Lunch" ExpenseAmount="50" />
<Expense ExpenseReason="Transportation" ExpenseAmount="50" />
</Person>
<Person Name="Lisa" Department="Marketing">
<Expense ExpenseReason="Document printing" ExpenseAmount="50"/>
<Expense ExpenseReason="Gift" ExpenseAmount="125" />
</Person>
</Expenses>
</XmlDataSource>

Next, we define the DataTemplates to bind this data against our TreeView. None of this should look foreign if you already played with creating templates against the ObjectDataSource. (The big changes are basically adding X to Path and @ in the binds. Pretty simple if you've played with XML much.)

<HierarchicalDataTemplate DataType="Person" ItemsSource ="{Binding XPath=Expense}">
<TextBlock>
<TextBlock TextContent="{Binding XPath=@Name}"/>,
<TextBlock TextContent="{Binding XPath=@Department}"/>
</TextBlock>
</HierarchicalDataTemplate>

<DataTemplate DataType="Expense">
<TextBlock>
$<TextBlock TextContent="{Binding XPath=@ExpenseAmount}"/>,
<TextBlock TextContent="{Binding XPath=@ExpenseReason}"/>
</TextBlock>
</DataTemplate>

Finally, we bind the ItemsSource of our TreeView against our new DataSource. Simple.

<tv:TreeView ItemsSource="{Binding Source={StaticResource ExpenseDataSource}, XPath=Person}"/>

Here's a screenshot of the final thing. I've update the project I posted last time with the code for XMLDataSource (while keeping the ObjectDataSource against the file system). I also had some fun creating XAML folder icons. As with all source I post, it's provided as-is, your mileage may vary, void where prohibited, yadda yadda yadda.