Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use DynamicResource in the code behind?

I'd like to be able to set a property to a dynamic resource programmatically.

myControl.Property = this.Resource[key]

is not a valid response, since if the resource with the key 'key' is replaced, the property is not updated automatically.

Thanks for you response,

like image 708
Nicolas Dorier Avatar asked Nov 17 '09 19:11

Nicolas Dorier


2 Answers

A static resource won't update whether you do it in code or XAML. You'll need a dynamic resource for that.

In XAML:

<Grid x:Name="grid" Background="{DynamicResource Brush}"/>

In code:

grid.SetResourceReference(Grid.BackgroundProperty, "Brush");
like image 148
Kent Boogaart Avatar answered Nov 15 '22 05:11

Kent Boogaart


Be aware that DynamicResource is not available in Silverlight; it is only in WPF (Silverlight only has StaticResource).

Since you tagged your question both Silverlight and WPF, I suspect that you may be looking for a solution that works in both. If that is the case, you will probably want to use data binding instead of resources since you require the property to update in response to changes.

like image 35
KeithMahoney Avatar answered Nov 15 '22 07:11

KeithMahoney