tags:

views:

184

answers:

2

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,

+1  A: 

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");

HTH,
Kent

Kent Boogaart
No you are wrong, if the resource is changed by another one, static resource will update the target.StaticResource doesn't update if a property of the resource change, that's all.
Nicolas Dorier
Sorry, but you're wrong. The whole point of static resources is they are resolved at compile time. You can do a simple test to prove this.
Kent Boogaart
No way, I was so sure of myself, how I could believe that !!! sorry man, maybe the right question was "how to use DynamicResource in the code behind so :p"
Nicolas Dorier
No problems, Nicolas :)
Kent Boogaart
+1  A: 

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.

KeithMahoney
yeah, I didn't know DynamicResource was not available in SL, I update the tags, do you have any idea for WPF ?
Nicolas Dorier
Nicolas, I don't follow. Haven't I answered your question for WPF?
Kent Boogaart
You told me to use databinding instead of resources, but how can I, with databinding in the code behind, bind a dependency property to a resource (so that when the resource is replaced by a new one, my DP is updated).I don't see how I can do that with a binding.
Nicolas Dorier
@Nicolas: read my answer again. I didn't say that at all. I suggested `SetResourceReference`, which does exactly what you require. When the resource with the specified key is changed, the resource reference will ensure the change is applied to the relevant dependency property.
Kent Boogaart