Search code examples
xamarin.formsdata-bindingresourcedictionary

Xamarin.Forms Define StaticResources with Databinding


In my app, I obtain some styles from the server. So I defined a Data Model ("GlobalStyles") that exposes these styles as properties, e.g. Color MyColor1 and Color MyColor2. I would like to define these styles as Static Resources. How ist this done?

In my example, property "Color_1" of view MyView is set to MyColor1 and "Color_1" to MyColor2. However, when view MyView is located within a view with databinding to another model (e.g. "MyData"), MyColor1 and MyColor2 are tried to obtain from "MyData" and default values are taken.

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:ct="clr-namespace:xxx.Controls"
             xmlns:model="clr-namespace:xxx.Models" 
             x:Class="xxx.App">
    <Application.Resources>
        <ResourceDictionary>
            <model:GlobalStyles x:Key="BaseStyles" />
            <Style TargetType="ct:MyView" >
                <Setter Property="BindingContext" Value="{StaticResource BaseStyles}"/>
                <Setter Property="Color_1" Value="{Binding MyColor1}"/>
                <Setter Property="Color_2" Value="{Binding MyColor2}"/>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Another way is to define static resources like

 <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="Primary">#65a83e</Color>
        </ResourceDictionary>
    </Application.Resources>

and refer to this resource as

Value="{StaticResource Primary}"

But how to replace #65a83e by a property of "GlobalStyles"?


Solution

  • I worked around this Problem by setting the ResourceDictionary entries in codebehind:

            ResourceDictionary dict = Application.Current.Resources;
            dict["Prop1"] = globalStyles.Prop1;
            dict["Prop2"] = globalStyles.Prop2;
            dict["Prop3"] = globalStyles.Prop3;