WPF TreeViewItem default icon for each parent node

493 views Asked by At

How would I add an icon to each of these parent nodes I tried adding under each TreeViewItem but the icon doesn't show and when I bind my collection to the ItemSource, it says it must be empty fist.

<TreeView x:Name="tvMessages" HorizontalAlignment="Left" Height="262" Margin="10,37,0,0" VerticalAlignment="Top" Width="248">
                <TreeViewItem x:Name="itemsCritical" Header="Critical">
                    <TreeViewItem.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Description}"/>
                                <TextBlock Text="{Binding ID}" Visibility="Hidden"/>
                            </StackPanel>
                        </DataTemplate>
                    </TreeViewItem.ItemTemplate>
                </TreeViewItem>
                <TreeViewItem x:Name="itemsAlert" Header="Alert">
                    <TreeViewItem.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Description}"/>
                                <TextBlock Text="{Binding ID}" Visibility="Hidden"/>
                            </StackPanel>
                        </DataTemplate>
                    </TreeViewItem.ItemTemplate>
                </TreeViewItem>
                <TreeViewItem x:Name="itemsInformational" Header="Informational">
                    <TreeViewItem.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Description}"/>
                                <TextBlock Text="{Binding ID}" Visibility="Hidden"/>
                            </StackPanel>
                        </DataTemplate>
                    </TreeViewItem.ItemTemplate>
                </TreeViewItem>
            </TreeView>
1

There are 1 answers

0
dev hedgehog On BEST ANSWER

Take a look at this example:

<TreeViewItem Name="treeViewItem1" IsEnabled="True">
    <TreeViewItem.Header>
        <StackPanel Orientation="Horizontal">
            <Image Height="16" Source="Images/16x16_red_lamp.png" Width="16" />
            <TextBlock Margin="5,0" Text="HostA: Disconnected" />
        </StackPanel>
    </TreeViewItem.Header>
</TreeViewItem>

Just place the Image inside and tell the Source where is your Icon located.

You can also use HeaderTemplate in case you have Bindings against associated item.