tags:

views:

2728

answers:

3

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?

+4  A: 

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>
James Osborn
+5  A: 

I think one of the best articles that will help you to understand the TreeView is this one http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx. In general, this describes a good set of patterns that can make a lot of scenarios in WPF/SL much easier.

EisenbergEffect
+3  A: 

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>
Zack Peterson