Its been a while since I’ve had to mess with the syntax to actually hook up an XML data set using XElement to a WPF TreeView. I’ve tried to recreate a pretty simple example, but I get nothing displaying in the TreeView.
Here is my XAML
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="ViewEditTreeTemplate">
<StackPanel Orientation="Horizontal" Margin="1">
<Label x:Name="ElementHeaderLabel" Content="{Binding Path=Name.LocalName}" />
</StackPanel>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView Name="DataTree" ItemsSource="{Binding Source={StaticResource ViewEditTreeTemplate}}" Height="160" Width="176" />
</Grid>
And here is the code behind.
XElement Element = XElement.Load("test.xml");
DataTree.DataContext = Element;
The “test.xml” is properly formatted and there are no errors while loading it. I don’t understand why nothing displays after I set the data context.
You did not set the
ItemTemplateof the TreeView (you appear to have accidentally set it asItemsSource) and you cannot implicitly apply templates to XML data making it a resource (further you set a Key which prevents that either way).I think in code behind you should set the
ItemsSourceinstead of theDataContext, it should be either a list of root elements or a one-element-list containing the root element only.