how to use DynamicResource in the code behind?

2019-04-29 06:34发布

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条回答
Ridiculous、
2楼-- · 2019-04-29 07:20

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");
查看更多
Rolldiameter
3楼-- · 2019-04-29 07:29

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.

查看更多
登录 后发表回答