Xamarin.Forms: Performance differences in using DynamicResource over StaticResource

311 Views Asked by At

I've seen a few questions asked around the performance difference in using DynamicResource over StaticResource but it's mainly been around WPF and not Xamarin.Forms mobile apps.

The context of my question is around a specific use-case I've got:

I have an application that only uses StaticResources at the moment but need the ability to have a 'flavour' of the app (determined by an internal build time flag) that is able to change the style/theme at runtime -- the variables to be controlled via an API upon app initialisation.

So I'm currently facing the situation where I would need to change all StaticResource references in the XAML layouts to use DynamicResource. What are the performance implications of this?

Alternatively, would it be possible to write my own markup extension to return if it should use DynamicResource or a StaticResource depending on the internal 'flavour' flag that is currently set? So that way I don't need to ship code that references dynamic resources if the flavour does not require it to do so.

1

There are 1 best solutions below

3
Adrain On

According to offical document Dynamic Styles in Xamarin.Forms:

The DynamicResource markup extension is similar to the StaticResource markup extension in that both use a dictionary key to fetch a value from a ResourceDictionary. However, while the StaticResource performs a single dictionary lookup, the DynamicResource maintains a link to the dictionary key. Therefore, if the dictionary entry associated with the key is replaced, the change is applied to the visual element. This enables runtime style changes to be made in an application.

Edit: The dynamicResources will override the staticresources if they both exist. I did a test about change staticresources into dynamic.

Xmal:

 <ContentPage.Resources>
        <Style TargetType="Label">
            <Setter Property="FontAttributes"
                    Value="Bold"/>
            <Setter Property="TextColor"
                    Value="Red"/>
        </Style>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!" x:Name="MyLabel"/>
            <Button Clicked="OnButton_Clicked"/>
        </StackLayout>
    </ContentPage.Content>

codebehind:

public Page1(bool IsDynamic)
    {
        var dynamicstyle = new Style(typeof(Label)) {
            Setters = { new Setter { Property=Label.FontProperty,
            Value="Bold"},
            new Setter{
            Property=Label.TextColorProperty,
            Value="Blue"} }
        };
        InitializeComponent();
        if (IsDynamic)
        { MyLabel.Style = dynamicstyle; }
    }
    private void OnButton_Clicked(object sender,EventArgs e)
    {
        Navigation.PushAsync(new Page1(true));

    }