开发者

How to assign a dynamic resource style in code?

开发者 https://www.devze.com 2022-12-12 07:11 出处:网络
I want to produce in code the equivalent of this in XAML: <TextBlock Text=\"Title:\" Width=\"{Binding FormLabelColumnWidth}\"

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


You should use FrameworkElement.SetResourceReference if you want true DynamicResource behaviour - ie updating of the target element when the resource changes.

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.


This should work:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消