How can I reference runtime static resources in WPF?

I created 2 image resources and I want to dynamically reference them from within the HierarchicalDataTemplate of the TreeView control.

This is my XAML code:

  <TreeView Margin="17,22" Name="TreeView">
                <TreeView.Resources>
                    <BitmapImage x:Key="Icon1" UriSource="pack://application:,,,/icon1.ico"/>
                    <BitmapImage x:Key="Icon2" UriSource="pack://application:,,,/icon2.ico"/>
                </TreeView.Resources>
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{StaticResource Icon1}" Margin="0,0,5,0" Width="16" Height="16"/>
                            <TextBlock Text="{Binding Name}" Margin="0,2,0,0" FontWeight="Normal" FontSize="11"/>
                        </StackPanel>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

What is the correct syntax for attaching a source to an image so that I can select a static image at runtime?

+3
source share
2 answers

You are already attached to some property Name. Extend the model (view-) with the integer property Icon, which determines with the icon you want to display for this entry. Then you can use a trigger:

<Image Margin="0,0,5,0" Width="16" Height="16">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="{StaticResource Icon1}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Icon}" Value="2">
                    <Setter Property="Source" Value="{StaticResource Icon2}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
+2
source

?

BitmapImage b = (BitmapImage)TreeView.FindResource("Icon1");

.

0

Source: https://habr.com/ru/post/1778595/


All Articles