How do I add icons next to the nodes in a WPF TreeView?

前端 未结 3 1621
太阳男子
太阳男子 2020-12-31 17:00

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

相关标签:
3条回答
  • 2020-12-31 17:15

    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>
    
    0 讨论(0)
  • 2020-12-31 17:28

    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.

    0 讨论(0)
  • 2020-12-31 17:32

    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>
    
    0 讨论(0)
提交回复
热议问题