With the following XML below I would like to use a hierarchicaldatatemplate
with a WPF treeview.
Depending on value in type I intend to use a different images with the name next to it and then to get the name from the value from the id tag.
<key type='Configuration'>
<id field='name' value='Some value'/>
</key>
<key type='Container'>
<id field='name' value='MyName'/>
<key type='Container'>
<id field='name' value='Data12345'/>
<key type='Container'>
<id field='name' value='Data987655'/>
<key type='Circuit'>
<id field='name' value='Data63236723'/>
</key>
</key>
</key>
</key>
I have tried some of the simple examples but none of them show how to use hierarchicaldatatemplate with attributes and also how the get the text with binding from the attributes.
Would be great if anyone could show how the hierarchicaldatatemplate should look like for this XML to be used with a TreeView.
At first, I thought that you couldn't fulfil those requirements with that XML schema. However, after trying it out in a test project, it seems that it all works just fine:
You'll need to use an XmlDataProvider
to access the XML file:
<XmlDataProvider Source="/WpfApplication2;component/Xml/TestXMLFile.xml"
XPath="root/key" />
You'll also need to add a root
node to the XML to make it legal:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<key type='Configuration'>
<id field='name' value='Some value'/>
</key>
<key type='Container'>
<id field='name' value='MyName'/>
<key type='Container'>
<id field='name' value='Data12345'/>
<key type='Container'>
<id field='name' value='Data987655'/>
<key type='Circuit'>
<id field='name' value='Data63236723'/>
</key>
</key>
</key>
</key>
</root>
Then you need to add the TreeView
:
<TreeView ItemsSource="{Binding}" ItemTemplate="{StaticResource ItemTemplate}" />
And then finally, add the HierarchicalDataTemplate
into your Resources
section:
<HierarchicalDataTemplate x:Key="ItemTemplate" ItemsSource="{Binding XPath=key}" DataType="key">
<StackPanel Orientation="Horizontal" Margin="0,2">
<Image>
<Image.Style>
<Style>
<Setter Property="Image.Source" Value="Images/Default.png" />
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=@type}" Value="Container">
<Setter Property="Image.Source" Value="Images/Container.png" />
</DataTrigger>
<DataTrigger Binding="{Binding XPath=@type}" Value="Configuration">
<Setter Property="Image.Source" Value="Images/Configuration.png" />
</DataTrigger>
<DataTrigger Binding="{Binding XPath=@type}" Value="Circuit">
<Setter Property="Image.Source" Value="Images/Circuit.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<TextBlock Text="{Binding XPath=id/@value}" Margin="5,0" />
</StackPanel>
</HierarchicalDataTemplate>
I didn't really mean to do the whole thing for you, so I'll leave you to tweak it to your liking. I trust you'll be ok from here.