Skip to content

Instantly share code, notes, and snippets.

@kyle-seongwoo-jun
Last active December 23, 2017 05:31
Show Gist options
  • Save kyle-seongwoo-jun/d5a42f6f943015df1a45d25d77ec9de8 to your computer and use it in GitHub Desktop.
Save kyle-seongwoo-jun/d5a42f6f943015df1a45d25d77ec9de8 to your computer and use it in GitHub Desktop.
How to apply a theme in Xamarin.Forms
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ThemeDemo.App">
<Application.Resources>
<ResourceDictionary>
<Color x:Key="BackgroundColorDark">#121212</Color>
<Color x:Key="BackgroundColorLight">#ffffff</Color>
<Color x:Key="BackgroundColorBrown">#292220</Color>
<Color x:Key="BarBackgroundColorDark">#2e2e2e</Color>
<Color x:Key="BarBackgroundColorLight">#d3d3d3</Color>
<Color x:Key="BarBackgroundColorBrown">#3c3835</Color>
<Color x:Key="TextColorDark">#ffffff</Color>
<Color x:Key="TextColorLight">#444444</Color>
<Color x:Key="TextColorBrown">#ffffff</Color>
</ResourceDictionary>
</Application.Resources>
</Application>
using Xamarin.Forms;
namespace ThemeDemo
{
public enum Theme
{
Dark, Light, Brown
}
public partial class App : Application
{
static readonly string[] resources = new string[] { "BackgroundColor", "BarBackgroundColor", "TextColor" };
Theme theme;
public Theme Theme
{
get => theme;
set
{
theme = value;
foreach (var resource in resources)
{
Resources[resource] = Resources[$"{resource}{theme}"];
}
}
}
public App()
{
InitializeComponent();
Theme = Theme.Dark;
var page = new NavigationPage(new MainPage());
// in C# code
page.SetDynamicResource(NavigationPage.BarTextColorProperty, "TextColor");
page.SetDynamicResource(NavigationPage.BarBackgroundColorProperty, "BarBackgroundColor");
MainPage = page;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ThemeDemo.MainPage"
Title="Theme Demo">
<ContentPage.Content>
<StackLayout BackgroundColor="{DynamicResource BackgroundColor}">
<Button Text="Change theme!"
FontSize="Large"
Clicked="Button_Clicked"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
using System;
using Xamarin.Forms;
namespace ThemeDemo
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
int index = 1;
private void Button_Clicked(object sender, EventArgs e)
{
var app = App.Current as App;
app.Theme = (Theme)(index++ % 3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment