How to assign a dynamic resource style in code?

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.


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