我可以在Xamarin表单中创建样式主题吗?
本文关键字:样式 创建 Xamarin 表单 我可以 | 更新日期: 2023-09-27 17:49:52
我目前有我所有的样式在我的App.xaml文件。是否有一种方法可以将它们分组为一个主题,以便我可以多个应用程序主题并随意更改?
据我所知,Xamarin没有内置主题支持。表单,但你可以实现一个。你需要做的是:1. 在你的App.xaml中添加一些具有相同样式的resourcedictionary。
<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}" />
我创建了一个示例应用程序,您可以在这里找到。如果你有任何问题,欢迎提问。
另一种解决方案是在应用启动/视图初始化时替换资源。如果您已经有一个项目,其中包含了整个项目的Styles和StaticResource引用,而不是将所有引用更新到DynamicResource,您可以为您的主题创建第二个带有样式的XAML字典。一个缺点是,它可能需要重新加载应用程序。
。你可以在App.xaml全局资源中设置默认主题,在WhiteTheme.xaml中设置白色主题样式覆盖。在创建视图时,您可以检查主题是否不是默认的(例如通过App.Current.Properties.ContainsKey(nameof(WhiteTheme)),遍历非默认资源字典中的所有键,并将它们替换为默认字典中的键:
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的例子。