8
votes

I have a Xamarin Forms application which gives the user 3 theme options. I want to be able to change the Tabbar background, selected item and unselected item color with a button click. In iOS I was able to do this with a renderer like below:

protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
    base.OnElementChanged(e);

    if(e.OldElement != null)
    {
        Xamarin.Forms.Application.Current.PropertyChange -= Current_PropertyChanged;
        return;
    }

    Xamarin.Forms.Application.Current.PropertyChange += Current_PropertyChanged; //subscribe to the App class' built in property changed event
    UpdateTheme();
}

void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    UpdateTheme();
}

In Android, I know its possible to change these colors in styles.xml but that would only allow me to set the colors once. Also, I am using the ToolbarPlacement="Bottom" to place my tab bar at the bottom of the screen.

android:TabbedPage.ToolbarPlacement="Bottom"
android:TabbedPage.BarSelectedItemColor="Red"
android:TabbedPage.IsSwipePagingEnabled="False"

I wonder if its possible to be able to change the BarSelectedItemColor dynamically with a button click.

2

2 Answers

7
votes

I have finally made this working by using DynamicResource styling:

From this:

android:TabbedPage.BarSelectedItemColor="Red"

To this:

android:TabbedPage.BarSelectedItemColor="{DynamicResource BarSelectedItemColor"
0
votes

You can Check this link.

This is talk about dynamic Resource and Them or some thing like that.

<Application>
    xmlns="zamarin schema{forms}"
    xmlns:x="microsoft schema{xaml}"
    x:Class="name">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="backgroundColor">your color</Color>
            <Color x:Key="textColor">name of color</Color>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Static Resources

The StaticResource markup extension allows us to reference predefined resources, but have one key limitation: resources from the dictionary are only fetched one time during control instantiation and cannot be altered at runtime. The syntax is very similar to that for bindings; just set the property’s value to “{StaticResource Resource_Name}”. Let’s update our ViewCell to use the resources we defined:

<Label Text="{Binding Name}" FontSize="Medium" FontAttributes = "Bold" TextColor = "{DynamicResource textColor}" LineBreakMode="NoWrap"/>
<Label Text="{Binding Text}" FontSize="Small" LineBreakMode="WordWrap" TextColor = "{DynamicResource textColor}"/>

Now! in this code you can change your resource:

App.Current.Resources ["backgroundColor"] = Color.White;
App.Current.Resources ["textColor"] = Color.Black;