且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不同的 WPF Treeview 图标取决于节点的类型

更新时间:2023-02-08 22:35:29

这是我用来解决几乎相同问题的一些代码.(我设计这个的数据是XML数据,所以XPath="@name"表示节点属性名的值,而Name表示元素类型.)

Here is some code I used to solve almost the same problem. (The data I designed this for is XML data, so XPath="@name" means the value of the attribute name of the node, while Name means element type.)

<Window x:Class="NodeExplorer2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:NodeExplorer2">
    <Window.Resources>
        <my:PathConverter x:Key="iconConverter"/>

        <HierarchicalDataTemplate x:Key="XmlTreeTemplate">
            <HierarchicalDataTemplate.ItemsSource>
                <Binding XPath="child::node()" />
            </HierarchicalDataTemplate.ItemsSource>

            <StackPanel Orientation="Horizontal">
                <Image x:Name="icon" SnapsToDevicePixels="True" Stretch="None" Margin="0,0,3,0" />
                <TextBlock Text={Binding XPath="@name"/>
            </StackPanel>
            <HierarchicalDataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
                    <Setter TargetName="icon" Property="Source">
                        <Setter.Value>
                            <Binding Path="Name" Converter="{StaticResource iconConverter}">
                                <Binding.FallbackValue>
                                    <ImageSource>
                                        Data/Icons/unknown.png
                                    </ImageSource>
                                </Binding.FallbackValue>
                            </Binding>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </HierarchicalDataTemplate.Triggers>
        </HierarchicalDataTemplate>

转换器:

public class PathConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //Console.WriteLine("Value:" + value);
            return "Data/Icons/" + value + ".png";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return "";
    }
}