7

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,

2 Answers 2

18

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"); 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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"
0

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.

4 Comments

yeah, I didn't know DynamicResource was not available in SL, I update the tags, do you have any idea for WPF ?
Nicolas, I don't follow. Haven't I answered your question for WPF?
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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.