简体   繁体   English

如何在代码中分配动态资源样式?

[英]How to assign a dynamic resource style in code?

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 = ???

如果您想要真正的 DynamicResource 行为,您应该使用FrameworkElement.SetResourceReference - 即在资源更改时更新目标元素。

tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")

You can try:你可以试试:

tb.Style = (Style)FindResource("FormLabelStyle");

Enjoy!享受!

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.上面的最佳答案使用了 SetResourceReference。 For the Xamarin framework this is not available but SetDynamicResource is and it does exactly what the original poster was asking.对于 Xamarin 框架,这不可用,但 SetDynamicResource 可用,它完全符合原始海报的要求。 Simple example简单的例子

        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.这应该适用于任何财产。

这应该有效:

tb.SetValue(Control.StyleProperty, "FormLabelStyle");

Application.Current.Resources.TryGetValue("ResourceKey", out var value)

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

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