UWP setting themeresource acrylic in code behind

UWP setting themeresource acrylic in code behind

我有一个 UWP 应用程序,我想将它升级到流畅的设计系统。我使用 Windows Template Studio 创建了一个新项目,我的导航是使用 Pivot。

现在我想把亚克力背景放在枢轴的header上。如 uwp 的设计指南中所述,建议在这种情况下使用 70% 的亚克力。

所以我尝试使用 70% 的亚克力和以下代码。

private void MainPivot_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.AcrylicBrush"))
    {
        MainPivot.Background = Application.Current.Resources["SystemControlAltHighAcrylicWindowBrush"] as AcrylicBrush;
    }

}

其中 MainPivot 是我正在使用的枢轴,此加载方法是该枢轴的加载事件。

问题是它仅适用于 LightDark 主题(取决于上次 [=39= 期间设置的主题) ]),但是当应用程序 运行ning 并且我更改主题并在浅色或深色主题之间切换时,它对两个主题都不起作用,例如,如果我将主题设为深色,则丙烯酸颜色仍然存在白色和枢轴 header 文本也是白色因此造成干扰 UI.

此外,后备颜色 也没有意义,因为浅色主题的后备颜色是黑色(与黑色文本混合),同样的问题出现在深色主题中。

我之所以从后面的代码中做到这一点,是因为我的应用程序的最小项目目标是没有丙烯酸笔刷的创作者更新。

Conditional XAML 提供了一种在 XAML 标记中使用 ApiInformation.IsTypePresent 方法的方法。这使您可以根据 API 的存在在标记中设置属性和实例化对象,而无需使用代码隐藏。

要在 XAML 中使用条件方法,您必须首先在页面顶部声明条件 XAML 命名空间。

xmlns:IsAcrylicBrushPresent="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush)"
xmlns:IsAcrylicBrushNotPresent="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsTypeNotPresent(Windows.UI.Xaml.Media.AcrylicBrush)"

命名空间定义好后,我们可以使用你的GridBackground属性的命名空间前缀来限定它是应该设置的属性在运行时有条件地。

<Grid Name="MainPivot" IsAcrylicBrushPresent:Background="{ThemeResource SystemControlAltHighAcrylicWindowBrush}"  IsAcrylicBrushNotPresent:Background="Red">

如果设备支持AcrylicBrush,它将使用SystemControlAltHighAcrylicWindowBrush。如果不是,它将使用红色。