我可以在 Xamarin Forms 中创建样式主题吗?

Can I create Style Themes in Xamarin Forms?

我目前的所有样式都在我的 App.xaml 文件中。有没有办法将它们分组为一个主题,以便我可以使用多个应用程序主题并随意更改?

据我所知,Xamarin.Forms 中没有内置的主题支持,但您可以实现一个。 你需要做的: 1. 向您的 App.xaml 添加一些具有相同样式列表的 ResourceDictionaries。

<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="ThemeTest.App">
  <Application.Resources>
  </Application.Resources>
  <ResourceDictionary x:Name="Default">
    <Style x:Key="labelStyle" TargetType="Label">
      <Setter Property="TextColor" Value="Green" />
    </Style>
  </ResourceDictionary>
  <ResourceDictionary x:Name="Second">
    <Style x:Key="labelStyle" TargetType="Label">
      <Setter Property="TextColor" Value="Yellow" />
    </Style>
  </ResourceDictionary>
</Application>

2。在您的 App.xaml.cs 中添加代码以在样式之间切换。

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        SetDefaultStyle();
        MainPage = new TestPage();
    }

    public void SetDefaultStyle()
    {
        Resources = Default;
    }

    public void SetSecondStyle()
    {
        Resources = Second;
    }
}

3。在 XAML 中使用 DynamicResource 标记扩展引用您的样式。

<Label Text="Test text" Style="{DynamicResource labelStyle}" />

我创建了您可以找到的示例应用程序 here。 Shell有什么问题欢迎提问

另一种解决方案是在应用 start/view 初始化时替换资源。如果您已经有一个项目,其 Styles 和 StaticResource 引用扩展到整个项目,而不是更新所有对 DynamicResource 的引用,您可以创建第二个 XAML 字典,其中包含您主题的样式。一个缺点,它可能需要重新加载应用程序。

例如您可以在 App.xaml 全局资源中使用默认主题,在 WhiteTheme.xaml 中使用白色主题样式覆盖。在创建视图时,您可以检查主题是否不是默认主题(例如通过 App.Current.Properties.ContainsKey(nameof(WhiteTheme) ),遍历非默认资源字典中的所有键和put/replace 默认字典中的键:

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            ApplyTheme();

            InitializeComponent();
        }

        private static void ApplyTheme()
        {
            if ((App.Current as App).WhiteTheme)
            {
                var whiteTheme = new WhiteTheme();

                foreach (var key in whiteTheme.Keys)
                {
                    if (Application.Current.Resources.ContainsKey(key))
                        Application.Current.Resources[key] = whiteTheme[key];
                }
            }
        }
    }

这里是 App.xaml, WhiteTheme.xaml and MainPage.xaml.cs 的例子。