I am trying to learn how to bind the following simple XML file to a WPF TreeView
:
<?xml version="1.0" encoding="utf-8" ?>
<Profiles>
<Customer>
<Name>Customer1</Name>
<Profile>
<Version>1.0</Version>
<DisplayText>DisplayText1</DisplayText>
</Profile>
<Profile>
<Version>1.0</Version>
<DisplayText>DisplayText2</DisplayText>
</Profile>
</Customer>
<Customer>
<Name>Customer2</Name>
<Profile>
<Version>1.0</Version>
<DisplayText>DisplayText3</DisplayText>
</Profile>
</Customer>
</Profiles>
Here is my XAML code of the attempt:
<TreeView DockPanel.Dock="Left" Height="auto" Name="treeView1" Width="217"
SelectedItemChanged="UIProfileTreeViewSelectedItemChanged"
ItemsSource="{Binding}">
<TreeView.DataContext>
<XmlDataProvider Source="Profiles.xml" XPath="/Profiles/Customer"/>
</TreeView.DataContext>
&l开发者_高级运维t;TreeView.Resources>
<DataTemplate DataType="Customer">
<TreeViewItem Header="{Binding XPath=Name}"
ItemsSource="{Binding XPath=Profile}"/>
</DataTemplate>
<DataTemplate DataType="Profile">
<TreeViewItem Header="{Binding XPath=DisplayText}" />
</DataTemplate>
</TreeView.Resources>
</TreeView>
However the results prevent me from selecting individual profiles under a customer in the TreeView
, if I click one profile the whole group gets highlighted like so:
alt text http://img38.imageshack.us/img38/4484/sberr.png
I clearly have a conceptual error with how databound items work. Any pointers?
I was able to get this to work with the xaml below.
There were two basic issues I ran into with your code:
- Both levels of your treeview were using "DataTemplate" instead of the "outer" one being defined as a "HierarchicalDataTemplate" -- so you had to put the ItemsSource on the TreeViewItem, which appears to have caused the "selection as a group" issue
I was having trouble getting selection to work at all using TreeViewItems, but after converting the DataTemplates to show a Label (you could display any sort of simple or complex set of controls in here), it worked perfectly. WPF automatically inserts "TreeViewItem" controls to wrap whatever you bind into a TreeView, so you don't need to do it explicitly.
<TreeView DockPanel.Dock="Left" Height="auto" Name="treeView1" Width="217" SelectedItemChanged="UIProfileTreeViewSelectedItemChanged" ItemsSource="{Binding}"> <TreeView.DataContext> <XmlDataProvider Source="Profiles.xml" XPath="/Profiles/Customer"/> </TreeView.DataContext> <TreeView.Resources> <HierarchicalDataTemplate DataType="Customer" ItemsSource="{Binding XPath=Profile}"> <Label Content="{Binding XPath=Name}" /> </HierarchicalDataTemplate> <DataTemplate DataType="Profile"> <Label Content="{Binding XPath=DisplayText}" /> </DataTemplate> </TreeView.Resources> </TreeView>
Hope this helps!
精彩评论