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

Solution 1:

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")

Solution 2:

You can try:

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

Enjoy!

Solution 3:

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.

Solution 4:

This should work:

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

Solution 5:

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