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

sga*_*dev 1 c# mono xaml xamarin xamarin.forms

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

Art*_*nov 6

据我所知,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>
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<Label Text="Test text" Style="{DynamicResource labelStyle}" />
Run Code Online (Sandbox Code Playgroud)

我创建了示例应用程序,您可以在此处找到.如果您有任何问题,欢迎您提出问题.