I have a wpf tree view that displays nodes of various types with corresponding images such as folder images. Initially, the tree and its nodes with corresponding images display
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
:
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>