简体   繁体   中英

How to assign a dynamic resource style in code?

I want to produce in code the equivalent of this in 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. For the Xamarin framework this is not available but SetDynamicResource is and it does exactly what the original poster was asking. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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