Xamarin.Forms - Switching between Dark & Light themes at run time

五迷三道 提交于 2019-12-05 10:45:18

The accepted answer doesn't adhere to the convention demonstrated by Microsoft.

Assuming you've installed the packages, Xamarin.Forms.Themes.Base, Xamarin.Forms.Themes.Light, and Xamarin.Forms.Themes.Dark, and your App.xaml looks like,

<?xml version="1.0" encoding="utf-8" ?>
<Application 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:light="clr-namespace:Xamarin.Forms.Themes;assembly=Xamarin.Forms.Theme.Light"
    xmlns:dark="clr-namespace:Xamarin.Forms.Themes;assembly=Xamarin.Forms.Theme.Dark"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MyNamespace.MyApp">
    <Application.Resources>
        <ResourceDictionary MergedWith="light:LightThemeResources">
            ...
        </ResourceDictionary>
    </Application.Resources>
</Application>

you can change the theme at run time with the following:

public enum Themes
{
    Dark,
    Light
}

var origin = App.Current.Resources;
switch (theme)
{
    case Themes.Dark:
        origin.MergedWith = typeof(DarkThemeResources);
        break;
    case Themes.Light:
        origin.MergedWith = typeof(LightThemeResources);
        break;
}

Yes is possible, adding the Resources by code in the App.cs class you can switch which Theme to use.

In the class constructor you set the default Theme:

Resources = new Xamarin.Forms.Themes.DarkThemeResources ();

You then expose a method is this class SwitchTheme() where you will assign the other theme:

public void SwitchTheme ()
{
    if (Resources?.GetType () == typeof (DarkThemeResources))
    { 
        Resources = new LightThemeResources ();
        return;
    }
    Resources = new DarkThemeResources ();
}

Be aware that if you have defined styles the code above won't work as it will override your Resources Dictionary. For that you could create your own themes based on these two, adding your define styles and use your implementations for switching.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!