Add icon to WPF TreeViewItem at runtime

SharpAffair picture SharpAffair · Dec 1, 2010 · Viewed 7.9k times · Source

There are many samples demonstrating this in XAML, such as the following:

<TreeViewItem>
<TreeViewItem.Header>
<StackPanel Orientation="Horizontal">
<Image Source="..."/>
<TextBlock>Hello</TextBlock>
</StackPanel>
</TreeViewItem.Header>

</TreeViewItem>

But I need to do this in runtime code - the purpose of TreeView is to show files and folders on the computer.

So I'm not sure how to work with Header in code:

 For Each f In directory.GetFiles()

        Dim icon = System.Drawing.Icon.ExtractAssociatedIcon(f.FullName)
        Dim name As String = f.Name    

        Dim item As New TreeViewItem
         item.Header = ...


 Next

Can anyone demonstrate the concept please?

EDIT: I think I'm getting it, I should use horizontal StackPanel with two separate controls - TextBlock and Image. Is this the right approach?

Answer

Nawaz picture Nawaz · Dec 1, 2010

.

Here is the sample code as to how you should start. Understand this first, and then make appropriate change to meet your need. The code written in C# and XAML. Hope you'll understand C# and would be able to convert it to Basic.

    public class NameIconPair
    {
        public String Name { get; set; }
        public BitmapSource IconSource { get; set; }
    }

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            var files = System.IO.Directory.GetFiles("E:\\");
            ObservableCollection<NameIconPair> pairs = new ObservableCollection<NameIconPair>();
            foreach (string file in files)
            {
                System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(file);
                Stream stream = new MemoryStream();
                icon.Save(stream);
                BitmapDecoder decoder = IconBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
                BitmapSource src = decoder.Frames[0];
                pairs.Add(new NameIconPair() { Name = file,  IconSource = src });
            }
            this.DataContext = pairs;
        }
    }

And here is the XAML code:

    <TreeView ItemsSource="{Binding}">
        <TreeView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding IconSource}"/>
                    <TextBlock Text="{Binding Name}"/>
                </StackPanel>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

Hope, this sample code would help you greatly. :-)

.