I’m creating my nodes (TreeViewItems) manually, I mean in code behind. I’m doing this because I’m loding subitems on demand when is expand and I have to add a dummy node. That’s the reason why I’m adding items manualy.
Now, the big deal is when I create a TreeViewItem does not display the DataTemplate and show the default. The output window does not tell anything.
DataTemplate dt1 = this.Resources["exerciseSetTemplate"] as DataTemplate;
foreach (var qs in qss)
{
TreeViewItem tvi = new TreeViewItem();
tvi.Header = qs.SetName;
tvi.Tag = qs;
tvi.ItemTemplate = dt1;
tvi.Items.Add(yourDummyNode);
treeView1.Items.Add(tvi);
}
Here is my XAML Code:
<UserControl.Resources>
<DataTemplate x:Key="questionSetTemplate">
<StackPanel Orientation="Horizontal" Height="20" Margin="2,0,2,0">
<Image Width="16" Height="16" Source="{StaticResource FolderImage}" Margin="0,0,5,0" />
<TextBlock Text="{Binding SetName}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<TreeView x:Name="treeView1" TreeViewItem.Expanded="treeView1_Expanded_1"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
</TreeView>
</Grid>
What can I do to display the DataTemplate?
I think the best option is to not add the objects directly to the
TreeViewItemsproperty (as this will ignore DataTemplates) and create aCollectionto add these items to and bind that to yourTreeView, Then you can remove thex:Keyproperty of yourDataTemplateand use theDataType, this will apply the template to any objects of that type in the collection to yourTreeView.Example:
Code: