2
votes

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 on a binding to the underlying object?

I want something equivalent to this

MyProperty="{StaticResource ResourceKey={Binding Path=MyProperty}}"

While this compiles, it will fail complaining it can't find a key of type System.Windows.Data.Binding

I don't need dynamic re-evaluation if the underlying value changes (eg DynamicResource)

2

2 Answers

3
votes

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
votes

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