how to use DynamicResource in the code behind?

2019-04-29 07:29发布

问题:

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


回答2:

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.