How to implement WPF TreeView with icons


[Sergei Meleshchuk. http://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.


 

Comments (4)

  1. Anita Gupta says:

    Thank you for making this so simple and saving me days of work.

  2. EVIL says:

    THIS is simple?? Thank God we have WPF! :))

  3. Philippe says:

    Hi,

    How can I exploit your function ? For get the SelectItem, when I clicking on the Treeview ?

    Best regards,

    Philippe G.

  4. xeilok dagger says:

    thank you so much! easily the best and simplest implementation i have seen thus far! XAML is still confusing to me lol!

    Thanks a ton again!