Setting up WPF treeview triggers to show different images on expand

▼魔方 西西 提交于 2019-12-03 07:47:47
H.B.

This question might be relevant.

As in my answer to the question I linked I would do the triggering in the image via RelativeSource binding, you can refactor that into a style so you do not have all that redundant code.

Possibly you could work with DynamicResources to provide the two images to every Image-control, or you could sub-class Image or create a UserControl which provides properties.


The DynamicResource method:

<TreeView.Resources>
    <Style x:Key="ExpandingImageStyle" TargetType="{x:Type Image}">
        <Setter Property="Source" Value="{DynamicResource Icon_Closed}"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}, Path=IsExpanded}" Value="True">
                <Setter Property="Source" Value="{DynamicResource Icon_Open}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TreeView.Resources>
<!-- Example usage -->
<HierarchicalDataTemplate DataType="{x:Type obj:Employee}">
    <StackPanel Orientation="Horizontal">
        <Image Style="{StaticResource ExpandingImageStyle}">
            <Image.Resources>
                <BitmapImage x:Key="Icon_Closed" UriSource="Images/FolderClosed.ico"/>
                <BitmapImage x:Key="Icon_Open" UriSource="Images/FolderOpen.ico"/>
            </Image.Resources>
        </Image>
        <TextBlock Text="{Binding Name}"/>
    </StackPanel>
</HierarchicalDataTemplate>

For completeness, the original setup with the HierarchicalDataTemplate triggers just needed to use a RelativeSource binding (as indicated by HB's answer), such as:

<HierarchicalDataTemplate DataType="{x:Type svm:SolutionsViewModel}" ItemsSource="{Binding Items, Mode=OneWay}">
    <StackPanel Style="{StaticResource TreeViewItemStackPanelStyle}">
        <Image x:Name="nodeImg" Style="{StaticResource IconImageStyleSmall}" Source="{StaticResource Icon_FolderClosed}" />
        <TextBlock Style="{StaticResource TreeViewItemTextStyle}" />
    </StackPanel>
    <HierarchicalDataTemplate.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}, Path=IsExpanded}" Value="True">
            <Setter TargetName="nodeImg" Property="Source" Value="{Binding Source={StaticResource Icon_FolderOpen}, Mode=OneTime}"/>
        </DataTrigger>
    </HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>

Below is an example image with different images on expand in the TreeView:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!