开发者

How do I refer at run-time to static resources in WPF?

I have created 2 image resources and I want to dynamically refer to them from inside the HierarchicalDataTemplate of a 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>
                开发者_如何学JAVA        <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 proper syntax for the Source binding of the image so that I can select at run-time which static image is shown?


You are already binding against some Name property. Extend your (view-)model with an integer property Icon that determines with Icon you want to be shown 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>


Do you mean the code-behind? In code-behind you can say

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

and then assign it to whichever property you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜