I have the need to create a HierarchicalDataTemplate for a TreeView in code-behind.
This is what my XAML looks like:
<DataTemplate x:Key="DetailTemplate">
<StackPanel Orientation="Horizontal">
<Image Height="15" Width="15" Source="{Binding Image}" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Text}" />
</StackPanel>
</DataTemplate>
<HierarchicalDataTemplate x:Key="MasterDetailTemplate"
ItemsSource="{Binding SomeSource}"
ItemTemplate="{StaticResource DetailTemplate}">
<StackPanel Orientation="Horizontal">
<Image Height="15" Width="15" Source="{Binding Image}" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Text}" />
</StackPanel>
</HierarchicalDataTemplate>
This is what i got so far in c#:
Image image = new Image();
image.Name = "image";
image.Height = 15;
image.Width = 15;
Binding imageBinding = new Binding("Image");
BindingOperations.SetBinding(image, Image.SourceProperty, imageBinding);
TextBlock textBlock = new TextBlock();
textBlock.Name = "textBlock";
Binding textBinding = new Binding("Text");
BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, textBinding);
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
stackPanel.Children.Add(image);
stackPanel.Children.Add(textBlock);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.DataTemplateKey
I am stuck at the DataTemplateKey.
- Is this possible to do in code behind?
- Where do i go from here to set the
x:Keyvalue?
OK In my comment to your question I specified the code behind way of specifying templates. Now to use / refer them with a key when we add them into ResourceDictionaties, we must add them with a Key.
Instead of
myWindowit can bemyParentPaneli.e. any ancestor of your tree view.But there is one issue..
The Key (i.e. the DataTemplate) doesnt exist at design time. You are creating and adding it at runtime.
So if you are referring this datatemplate then
Either refer the resource after it is are added to the resource dictionary.
e.g.
Refer the dynamically created data template as
DynamicResourcein XAML.DynamicResourceremoves the need of pre-existence ofMasterDetailTemplatein any resource dictionary.Hope this helps.