How to implement WPF TreeView with icons

[Sergei Meleshchuk. https://blogs.msdn.com/sergeim/\] 

The trick is to use StackPanel (example below). The StackPanel contains image and text. 

One of many ways to implement this is:

- Create folder with icons and deploy the folder to the same directory where the .exe file lives.
  Note: If using IDE, copy this folder from project directory to target with the post-build step:
  xcopy /sy "$(ProjectDir)icons\*" "$(TargetDir)icons\*"

- When initializing your app, compute location of the 'icons' folder:
    Settings.IconsFolder = GetIconFolder(); // IconsFolder is string

    where the 'GetIconsFolder' is like below:

private string GetIconFolder()

{

string execName =

Assembly.GetExecutingAssembly().

GetModules()[0].FullyQualifiedName;

string currentFolder = System.IO.

Path.GetDirectoryName(execName);

string icons = System.IO.Path.Combine(

currentFolder, "icons");

return icons;

}

 - Add TreeViewItem with the code like below:

TreeViewItem tvi = CreateTreeViewItem(

    "samplename",

    Settings.IconsFolder,

    "sample.ico");

treeView1.Items.Add(tvi);

where the 'CreateTreeViewItem' is your little wrapper:

private TreeViewItem CreateTreeViewItem(

string header,

string iconFolder,

string iconName)

{

    TreeViewItem child = new TreeViewItem();

    StackPanel pan = new StackPanel();

    if (iconName != null)

    {

        pan.Orientation = Orientation.Horizontal;

        IconBitmapDecoder icon = new IconBitmapDecoder(

            new Uri(System.IO.Path.Combine(

iconFolder,

iconName),

UriKind.RelativeOrAbsolute),

            BitmapCreateOptions.None,

            BitmapCacheOption.OnLoad);

        Image image = new Image();

        image.Height = 16;

        image.Source = icon.Frames[0];

        pan.Children.Add(image);

    }

    pan.Children.Add(new TextBlock(new Run(" " + header)));

    child.Header = pan;

    return child;

}

That's it.