#1,216 – Creating a Custom ItemTemplate in a TreeView

If we just want each node in a TreeView control to contain text, we can use a single TreeViewItem in the HierarchicalDataTemplate and bind its Header property to the text that we want displayed. However, we can use an Panel we like in the data template.

The example below builds on our last post, but using a Grid in a Border for each person in the tree.

<TreeView Grid.Row="0" Margin="5" ItemsSource="{Binding Royal}">
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <Border Background="AliceBlue" Margin="0,2,0,0" Padding="4,2,8,2" 
                    BorderBrush="DimGray" BorderThickness="1"

                    <TextBlock Grid.Row="0" Grid.Column="0" FontWeight="Bold"
                               Text="{Binding Name}"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" FontStyle="Italic"
                               Text="{Binding BirthDeath}" Margin="5,0,0,0"/>
                    <Image Grid.RowSpan="2" Grid.Column="2"
                           Height="20" Width="20" Margin="5,0"
                           Visibility="{Binding KingOrQueen, Converter={StaticResource BooleanToVisibilityConverter}}"/>

Here’s what the final result looks like (after I expand a few of the TreeView nodes: