Is it possible to dynamically create a ResourceKey for a StaticResource? (eg using a Binding)

后端 未结 2 1510
有刺的猬
有刺的猬 2021-01-15 03:33

Suppose the object I\'m binding to has a property with a string representing the ResourceKey - how do I get a StaticResource to dynamically acquire it\'s ResourceKey based o

相关标签:
2条回答
  • 2021-01-15 04:30

    I found exactly what I was looking for here:

    http://blog.functionalfun.net/2009/12/specifying-resource-keys-using-data_31.html

    It's a custom markup extension that behaves like a regular binding but the Path will point to a property that transforms the target into a ResourceKey and the binding will then return the resource!

    I've found this extremely useful!

    0 讨论(0)
  • 2021-01-15 04:31

    It's also possible to do it in the XAML code

    <MyControl.Resources>
        <Image x:Key="Image_1" Source="{StaticResource ResourceKey={x:Static img:ImageResourcesKeys.Image_1}}" x:Shared="false"/>
        <Image x:Key="Image_2" Source="{StaticResource ResourceKey={x:Static img:ImageResourcesKeys.Image_2}}" x:Shared="false"/>
        <Style TargetType="MyProperty">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ImageType}" Value="Image_1">
                    <Setter Property="MyProperty" Value="{StaticResource Image_1}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ImageType}" Value="Image_2">
                    <Setter Property="MyProperty" Value="{StaticResource Image_2}" />
                </DataTrigger>
             </Style.Triggers>
         </Style>
     </MyControl.Resources>
    

    All you need is a string property ImageType to choose the image you are going to use

    0 讨论(0)
提交回复
热议问题