Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...