C# 如何在代码中分配动态资源样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1754615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign a dynamic resource style in code?
提问by Edward Tanguay
I want to produce in code the equivalent of this in XAML:
我想在代码中生成与 XAML 等效的代码:
<TextBlock
Text="Title:"
Width="{Binding FormLabelColumnWidth}"
Style="{DynamicResource FormLabelStyle}"/>
I can do the text and the width, but how do I assign the dynamic resource to the style:
我可以做文本和宽度,但是如何将动态资源分配给样式:
TextBlock tb = new TextBlock();
tb.Text = "Title:";
tb.Width = FormLabelColumnWidth;
tb.Style = ???
采纳答案by Alastair Pitts
You can try:
你可以试试:
tb.Style = (Style)FindResource("FormLabelStyle");
Enjoy!
享受!
回答by robert.oh.
This should work:
这应该有效:
tb.SetValue(Control.StyleProperty, "FormLabelStyle");
回答by Samuel Hyman
You should use FrameworkElement.SetResourceReferenceif you want true DynamicResource behaviour - ie updating of the target element when the resource changes.
如果您想要真正的 DynamicResource 行为,您应该使用FrameworkElement.SetResourceReference- 即在资源更改时更新目标元素。
tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")
回答by user9220597
The original question was how to make it Dynamic, which means if the resource changes the control will update. The best answer above used SetResourceReference. For the Xamarin framework this is not available but SetDynamicResource is and it does exactly what the original poster was asking. Simple example
最初的问题是如何使它成为动态的,这意味着如果资源发生变化,控件将更新。上面的最佳答案使用了 SetResourceReference。对于 Xamarin 框架,这不可用,但 SetDynamicResource 可用,它完全符合原始海报的要求。简单的例子
Label title = new Label();
title.Text = "Title";
title.SetDynamicResource(Label.TextColorProperty, "textColor");
title.SetDynamicResource(Label.BackgroundColorProperty, "backgroundColor");
Now calling:
现在调用:
App.Current.Resources["textColor"] = Color.AliceBlue;
App.Current.Resources["backgroundColor"] = Color.BlueViolet;
Causes the properties to change for all controls using the resource this way. This should work for any property.
以这种方式使所有使用资源的控件的属性发生更改。这应该适用于任何财产。
回答by Abdul Gani
Application.Current.Resources.TryGetValue("ResourceKey", out var value)
Application.Current.Resources.TryGetValue("ResourceKey", out var value)