Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does data binding to DynamicResource not work?

Tags:

wpf

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

<Image Source="{DynamicResource {Binding VM.ImageKey}}" />
like image 740
Rohit Avatar asked Sep 17 '10 07:09

Rohit


2 Answers

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.

like image 160
bitbonk Avatar answered Nov 12 '22 06:11

bitbonk


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

like image 3
Rohit Avatar answered Nov 12 '22 07:11

Rohit