I have a WPF TreeView with just 1 level of items. The TreeView is data bound to an ObservableCollection of strings. How can I ensure that the same icon appears to the left of each node in the TreeView?
But in WPF, there is no direct support of adding the images at nodes of Tree View. As I mentioned above, in Windows Forms Tree View the process of adding the icons was very similar. TreeView control provides the ImageList property.
It is not a big deal to provide the icons functionality with Windows Forms Tree View. But in WPF, there is no direct support of adding the images at nodes of Tree View. As I mentioned above, in Windows Forms Tree View the process of adding the icons was very similar. TreeView control provides the ImageList property.
The Windows Forms TreeView control can display icons next to each node. The icons are positioned to the immediate left of the node text. To display these icons, you must associate the tree view with an ImageList control.
Set the TreeView control's ImageList property to the existing ImageList control you wish to use. These properties can be set in the designer with the Properties window, or in code. Set the node's ImageIndex and SelectedImageIndex properties.
I used James Osborn's StackPanel technique in this way...
XAML:
<TreeView Name="TreeViewThings" ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Thing}"
ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" Margin="2">
<Image Source="Thing.png"
Width="16"
Height="16"
SnapsToDevicePixels="True"/>
<TextBlock Text="{Binding Path=Name}" Margin="5,0"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
I think the best approach is to set a Style on the TreeView that will change the Template of the TreeViewItems to have the Image that you want.
The Template will probably need to be a StackPanel with an Image and a label control, you bind the image to your icon, and the label text to the strings from the Observable collection.
I've copied the relevant code snippet from a Code Project article, which covers this in more detail, but I think the below is all you'll need (This code goes in the TreeView.Resources element).
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="img"
Width="20"
Height="20"
Stretch="Fill"
Source="image.png"/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With