【问题标题】:Display image depending on application theme (Dark/light theme)根据应用程序主题显示图像(深色/浅色主题)
【发布时间】:2017-06-23 14:17:17
【问题描述】:

我正在开发一个 UWP 应用,我正在使用 template10。我有两张图片,一张是白色的,另一张是黑色的。我想在浅色主题中显示黑色图像,在深色主题中显示白色图像。我有这个代码:

if (this.RequestedTheme == ElementTheme.Light)
    Image.Source = new BitmapImage(new Uri("ms-appx:///Assets/BlackImage.png"));
else
    Image.Source = new BitmapImage(new Uri("ms-appx:///Assets/WhiteImage.png"));

但是,当我选择浅色主题图像时不会出现!但是当我选择深色主题时,会出现白色图像。

【问题讨论】:

  • 确保此代码有效,因为我已在我的应用程序中使用它。另外,如果您对此代码有任何问题,请在this 答案上发表评论。不要创建新帖子说答案无效。
  • 确保资产确实在您期望的位置,您确认黑色图像在那里吗?
  • 什么是this?是Application吗?还是Page?你也在Initialization 中使用它吗?或Button点击?

标签: c# uwp uwp-xaml


【解决方案1】:

如果我们不将ElementTheme.LightElementTheme.Dark 设置为FrameworkElement.RequestedTheme,它将始终返回ElementTheme.Default。因此,无论ApplicationThemeLight,您的图像都将设置为WhiteImage。

应用程序中的RequestedTheme 可以获取或设置一个值,该值确定应用程序整体主题的明暗偏好。它返回枚举的ApplicationTheme。它包括LightDark。我们应该可以使用App.Current.RequestedTheme来获取App当前的ApplicationTheme

例如:

var AppRequestedTheme = App.Current.RequestedTheme.ToString();
if (AppRequestedTheme == "Light")
    Image.Source = new BitmapImage(new Uri("ms-appx:///Assets/BlackImage.png"));
else
    Image.Source = new BitmapImage(new Uri("ms-appx:///Assets/WhiteImage.png"));

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 2015-10-04
    • 2022-08-12
    • 2021-11-29
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多