I'm having some problems changing the DataTemplate that is used for a TreeViewItem when it is selected. Ideally, I would like each item to contain a TextBlock
, and then when selected it should contain a TextBox
instead.
Here is what I have so far (I used this question as a starting point):
<Window>
<Window.Resources>
<HierarchialDataTemplate x:Key="normal"
ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Text}" />
</HierarchialDataTemplate>
<HierarchialDataTemplate x:Key="selected"
ItemsSource="{Binding Path=Children}">
<TextBox Text="{Binding Path=Text}" />
</HierarchialDataTemplate>
<Style TargetType="{x:Type TreeViewItem}" x:Key="ContainerStyle">
<Setter Property="ItemTemplate" Value="{StaticResource normal}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ItemTemplate" Value="{StaticResource selected}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resource>
<Grid>
<TreeView ItemSource="{Binding Body}" ItemContainerStyle="{StaticResource ContainerStyle}" />
</Grid>
</Window>
What happens is that there is only one node in the tree, and the text of the node is the type name of the object. It sounds like the type bound to the node isn't what the template is expecting, so it's using the default ToString()
binding instead of the Text
property as I specified.
I have set the DataContext of the Window in the code behind file. I know that my Bindings for the data are correct, because if I set one HierarchialDataTemplate
for the TreeView the data is displayed correctly.
I think that my problem is that I need to set a property other than ItemTemplate
in the TreeViewItem
styles - am I using the right property, or should I set something else?