tags:

views:

27

answers:

3

The following code does not work. How do I make it working

<Image Source="{DynamicResource {Binding VM.ImageKey}}" />
A: 

This is an incorrect usage of the DynamicResource MarkupExtension. Correct it would be:

<Image Source="{DynamicResource VM.ImageKey}" />

Assuming you have a resource with a key "VM.ImageKey" defined somewhere like this:

<Bla.Resources>
    <BitmapImage x:Key="VM.ImageKey" UriSource="C:\Uri\To\Image.jpg" />
</Bla.Resources>

However if you want to bind against some property form the current DataContext you must not use DynamicResource but Binding:

<Image Source="{Binding VM.ImageKey}" />

Assuming your current DataContext is an instance that has a property called VM wich again has a property called ImageKey wich is a derived type of ImageSource.

bitbonk
Also, if ImageKey is a static field or property on a VM class, you could use the {x:Static} syntax to retrieve it:<Image Source="{DynamicResource {x:Static lcl:VM.ImageKey}" />where lcl is the xmlns defined to the VM clr-namespace.
Abe Heidebrecht
A: 

If you want to specify the resource key dynamically you should specify it using the ResourceKey markup extension - not sure if it supports bindings in the way you want it to however. See here for more details.

Alex Paven
A: 

This behaviour is by design. Binding works only on dependency properties of dependency objects and MarkupExtension is not dependency object.

Rohit