WPF: TreeViewItem with Text and Icon
by admin 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";
July 4th, 2013 on 08:20
StackPanel holder = new StackPanel();
TreeViewItem itemTag = new TreeViewItem();
holder.Children.Add(new Image(){Source=});
holder.Children.Add(new TextBlock(){Text=});
itemTag.Header = holder;
August 29th, 2014 on 04:09
i am so glad that i found this beautiful site thanks a
million keep up
November 6th, 2016 on 12:26
Thank you for the code, it helped a lot! 🙂