beta.blog

WPF: TreeViewItem with Text and Icon

by on Jun.22, 2012, under Programming

I recently faced the problem of adding an icon to a WPF TreeViewItem. The following example code (XAML) demonstrates how I managed to add an icon in front of the text of my TreeViewItems as well as how to replace the icon or the text at runtime.

This is my result:

This is the XAML code of a TreeViewItem with icon. The icon file will be loaded from my Images subfolder.

<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>

And this is how I replace the image/text on the fly:

TreeViewItem itemTag = (TreeViewItem)treeView1.Items[0];
StackPanel holder = (StackPanel)itemTag.Header;
Image image = (Image)holder.Children[0];
TextBlock textBlock = (TextBlock)holder.Children[1];

image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"pack://application:,,,/TreeViewTestProject;component/Images/16x16_green_lamp.png"));
textBlock.Text = "HostA: Connected";

3 Comments for this entry

  • Seneran Owinda

    StackPanel holder = new StackPanel();
    TreeViewItem itemTag = new TreeViewItem();

    holder.Children.Add(new Image(){Source=});
    holder.Children.Add(new TextBlock(){Text=});
    itemTag.Header = holder;

  • pet29

    i am so glad that i found this beautiful site thanks a
    million keep up

  • Christian Larsson

    Thank you for the code, it helped a lot! 🙂

Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!