5

1 - 知道我们是否可以使用 2.3.x 版中引入的 Xamarin.Forms 主题在 Light & Dark 主题之间切换(链接如下)。任何解决方法? https://developer.xamarin.com/guides/xamarin-forms/user-interface/themes/

2 - 我还看到此版本自推出以来一直处于预览状态。是否有任何问题,我们不能在生产中使用它?

4

2 回答 2

5

接受的答案不符合Microsoft 展示的约定

假设您已安装包Xamarin.Forms.Themes.BaseXamarin.Forms.Themes.LightXamarin.Forms.Themes.Dark,并且您的App.xaml看起来像,

<?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>

您可以在运行时使用以下内容更改主题:

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;
}
于 2018-03-19T17:10:04.023 回答
3

是的,可以通过代码在 App.cs 类中添加资源,您可以切换要使用的主题。

在类构造函数中,您设置默认主题:

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

然后,您公开一个方法是这个类SwitchTheme(),您将在其中分配另一个主题:

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

请注意,如果您定义了样式,则上面的代码将不起作用,因为它将覆盖您的资源字典。为此,您可以基于这两个创建自己的主题,添加您定义的样式并使用您的实现进行切换。

于 2017-03-28T02:26:09.463 回答