How to use DynamicResource in code?

I would like to be able to set a property in a dynamic resource programmatically.

myControl.Property = this.Resource[key] 

This is not a valid answer, because if the resource with the key "key" is replaced, the property is not updated automatically.

Thanks for the answer,

+6
resources wpf
source share
2 answers

A static resource will not update whether you are doing this in code or XAML. For this you need a dynamic resource.

In XAML:

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

In code:

 grid.SetResourceReference(Grid.BackgroundProperty, "Brush"); 
+13
source share

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

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

+1
source share

All Articles