#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}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <Border Background="AliceBlue" Margin="0,2,0,0" Padding="4,2,8,2" 
                    BorderBrush="DimGray" BorderThickness="1"
                    CornerRadius="3">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>

                    <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"
                           Source="Crown.png"
                           Visibility="{Binding KingOrQueen, Converter={StaticResource BooleanToVisibilityConverter}}"/>
                </Grid>
            </Border>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

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