如何使用此“新功能”使我的应用程序响应。我现在想要一个唯一的灯光模式。我看到了这个
UIUserInterfaceStyle style = UIUserInterfaceStyle.Light;
如何在我的 Xamarin Forms 应用程序上激活它
如何使用此“新功能”使我的应用程序响应。我现在想要一个唯一的灯光模式。我看到了这个
UIUserInterfaceStyle style = UIUserInterfaceStyle.Light;
如何在我的 Xamarin Forms 应用程序上激活它
您可以通过创建两个资源来响应用户界面样式的变化:LightTheme 和 DarkTheme(它们将是 ResourceDictionaries)。在它们内部,您可以添加自定义颜色。例如:
LightTheme.xaml:
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkMode.Styles.LightTheme">
<Color x:Key="background">#FFFFFF</Color>
<Color x:Key="mainLabel">#000000</Color>
</ResourceDictionary>
DarkTheme.xaml:
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkMode.Styles.DarkTheme">
<Color x:Key="background">#000000</Color>
<Color x:Key="mainLabel">#FFFFFF</Color>
</ResourceDictionary>
然后,您必须为 ContentPage 元素创建一个 CustomRenderer(当然,仅适用于 iOS):
[assembly: ExportRenderer(typeof(ContentPage), typeof([YOUR_NAMESPACE].iOS.Renderers.PageRenderer))]
namespace [YOUR_NAMESPACE].iOS.Renderers
{
public class PageRenderer : Xamarin.Forms.Platform.iOS.PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
try
{
SetTheme();
}
catch(Exception ex)
{
}
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
if (TraitCollection.UserInterfaceStyle != previousTraitCollection.UserInterfaceStyle)
SetTheme();
}
private void SetTheme()
{
if (TraitCollection.UserInterfaceStyle == UIUserInterfaceStyle.Dark)
App.Current.Resources = new DarkTheme();
else
App.Current.Resources = new LightTheme();
}
}
}
更多信息。
您可以按照前面的评论对模式更改做出反应。如果你想在你的应用程序中设置模式,你可以通过Window.OverrideUserInterfaceStyle
在你AppDelegate.cs
的例子中进行设置,
Window.OverrideUserInterfaceStyle = UIUserInterfaceStyle.Dark;
这是有关如何在 Xamarin.Forms 中支持暗模式的完整博客文章, https: //intelliabb.com/2019/11/02/how-to-support-dark-mode-in-xamarin-forms/