- I wish to bind my TreeView to a datasource.
- The TreeView should build its child nodes dynamically (unknows childs in datasource).
- Each node should display its data or (if no data) its element name.
Solution
You need to use and understand these parts:
- HierarchicalDataTemplate
- HierarchicalDataTemplate.Triggers
- Binding XPath
Just copy paste and start playing / reading each part's help.
XAML
Code Snippet
- <Window x:Class="TreeViewDataBinding.Window1"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="Window1" Height="300" Width="300">
- <Window.Resources>
- <HierarchicalDataTemplate x:Key="NodeTemplate" >
- <TextBlock x:Name="tbName" Text="?" />
- <HierarchicalDataTemplate.ItemsSource>
- <Binding XPath="child::node()" />
- </HierarchicalDataTemplate.ItemsSource>
- <HierarchicalDataTemplate.Triggers>
- <DataTrigger Binding="{Binding Path=NodeType}" Value="Text">
- <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Value}"/>
- </DataTrigger>
- <DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
- <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Name}"/>
- </DataTrigger>
- </HierarchicalDataTemplate.Triggers>
- </HierarchicalDataTemplate>
- <XmlDataProvider x:Key="xmlDataProvider"/>
- </Window.Resources>
- <StackPanel>
- <Button Click="Button_Click">Reload</Button>
- <TreeView
- ItemsSource="{Binding Source={StaticResource xmlDataProvider}, XPath=*}"
- ItemTemplate="{StaticResource NodeTemplate}" />
- </StackPanel>
- </Window>
Code behind
Code Snippet
- using System.Windows;
- using System.Windows.Data;
- using System;
- namespace TreeViewDataBinding
- {
- public partial class Window1 : Window
- {
- public Window1()
- {
- InitializeComponent();
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- var provider = (XmlDataProvider)this.Resources["xmlDataProvider"];
- provider.Source = new Uri(@"Data\standard.xml", UriKind.Relative);
- }
- }
- }
Additional files
- standard.xml testbenach XML file (100MB !!).
- http://www.xml-benchmark.org/downloads.html
- " For your convenience, we provide a ready-made document for a 100 MB experiment."
Performance
I was able to load 100MB of xml data in around ~6 seconds first time, ~4 seconds from the second time.
Testbench station
- i7 (8 cores) @ 2.80GHz
- 4.00GB RAM
- 64-Bit OS, Win7 Pro.
CPU & memory usage
The CPU was at idle when i started, the RAM was at the base line.
Resources
- http://www.w3schools.com/xpath/xpath_syntax.asp
- http://www.w3schools.com/xpath/xpath_axes.asp
- http://stackoverflow.com/questions/1605062/treeview-bound-to-xmldataprovider-shows-data-in-editor-but-empty-when-run
Hope it helps.
TreeView data binding to hierarchical data source
ReplyDelete