简体   繁体   English

如何在后面的代码中使用DynamicResource?

[英]how to use DynamicResource in the code behind?

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. 不是有效的响应,因为如果替换了具有键“key”的资源,则不会自动更新该属性。

Thanks for you response, 谢谢你的回复,

A static resource won't update whether you do it in code or XAML. 无论您是在代码还是XAML中执行此操作,静态资源都不会更新。 You'll need a dynamic resource for that. 你需要一个动态资源。

In XAML: 在XAML中:

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

In code: 在代码中:

grid.SetResourceReference(Grid.BackgroundProperty, "Brush");

Be aware that DynamicResource is not available in Silverlight; 请注意,Silverlight中不提供DynamicResource; it is only in WPF (Silverlight only has StaticResource). 它只在WPF中(Silverlight只有StaticResource)。

Since you tagged your question both Silverlight and WPF, I suspect that you may be looking for a solution that works in both. 既然您将问题标记为Silverlight和WPF,我怀疑您可能正在寻找适用于这两者的解决方案。 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. 如果是这种情况,您可能希望使用数据绑定而不是资源,因为您需要更新属性以响应更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM