How to assign a dynamic resource style in code?

C#WpfXamlStylesCode Behind

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

You can try:

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

Enjoy!

Solution 3 - C#

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 - C#

This should work:

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

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdward TanguayView Question on Stackoverflow
Solution 1 - C#Samuel JackView Answer on Stackoverflow
Solution 2 - C#Alastair PittsView Answer on Stackoverflow
Solution 3 - C#user9220597View Answer on Stackoverflow
Solution 4 - C#robert.oh.View Answer on Stackoverflow
Solution 5 - C#Abdul GaniView Answer on Stackoverflow