问题
1 - Any idea if we can switch between Light & Dark themes using the Xamarin.Forms themes introduced in version 2.3.x (link below). Any workaround? https://developer.xamarin.com/guides/xamarin-forms/user-interface/themes/
2 - Also I see this release is in preview ever since it was introduced. Are there any issues and we cannot use it in production?
回答1:
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;
}
回答2:
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.
来源:https://stackoverflow.com/questions/42997914/xamarin-forms-switching-between-dark-light-themes-at-run-time