【问题标题】:Xamarin.Forms - Switching between Dark & Light themes at run timeXamarin.Forms - 在运行时在深色和浅色主题之间切换
【发布时间】:2019-12-28 06:15:20
【问题描述】:

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

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

【问题讨论】:

  • 谁能帮我解答我的问题?

标签: xamarin.forms xamarin.forms-styles


【解决方案1】:

接受的答案不符合the convention demonstrated by 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;
}

【讨论】:

  • MergedWith 没有过时。它仍然有效。有谁知道前进的方向吗?
【解决方案2】:

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

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

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

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

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

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

【讨论】:

  • 它有效。谢谢!然而,它似乎并没有改变标签页的主题。你知道我是否遗漏了什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2021-06-04
  • 2013-10-16
  • 1970-01-01
  • 2021-03-10
相关资源
最近更新 更多