如何在代码中更改Xaml资源中的颜色定义(UWP)

3

[UWP]

我有很多网格,它们使用从App.xaml绑定的颜色。

MainPage.xaml...

        <Grid
            Height="45"
            Margin="0,0,0,10"
            Background="{ThemeResource MyColor}">

App.xaml

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    RequestedTheme="Dark">
    <Application.Resources>
        <ResourceDictionary>
            <SolidColorBrush x:Key="MyColor">#FFFFFF</SolidColorBrush>

然后我想要更改所有的内容,代码如下:
    Application.Current.Resources["MyColor"] = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 242, 101, 34));

但它没有起作用。我可能漏掉了什么?当我导航到另一个页面并返回时,上面的代码会抛出System.Exception异常。


你说它“不工作”是什么意思?是抛出了异常,还是Grid的背景颜色没有改变? - Brandon Kramer
颜色没有改变。没有异常。 - HelloWindowsPhone
当我导航到另一个页面并返回时,上面的代码会抛出System.Exception异常。 - HelloWindowsPhone
4个回答

1

StaticResourceThemeResource不支持像WPF中的DynamicResource那样进行动态更改。顺便说一句,如果您重新加载视图,比如往返导航,您会看到更改,但这并不是一个好的解决方案。

另一方面,您可以通过ThemeResource实现一些动态更改,并根据当前主题(Dark,Light,High Contrast)更改颜色等。

进一步阅读: https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/xaml-theme-resources


但是我看到商店上有一些应用程序可以做到这一点。用户选择颜色后,颜色立即更改(例如:Windows 10商店中的Awesome Tube)。 - HelloWindowsPhone
1
他们很可能是使用绑定完成的,而不是像你所做的那样在代码中完成。 - Justin XL

0
(App.Current.Resources["MyColor"] as SolidColorBrush).Color = Windows.UI.Color.FromArgb(255, 242, 101, 34);

0

如果你知道它是一个SolidColorBrush,那么直接修改Color属性。

var brush = (SolidColorBrush)Application.Current.Resources["MyColor"];
brush.Color = Windows.UI.Color.FromArgb(255, 242, 101, 34);

如果您有权限,可以修改资源的属性,但无法更改资源本身。


0
我是这样做的:

App.xaml

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    RequestedTheme="Dark">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Dark">
                <Color x:Key="UserAccentColor">#FFFFA500</Color>
                <SolidColorBrush x:Key="UserAccentBrush" Color="{StaticResource UserAccentColor}"/>
            </ResourceDictionary>
            <ResourceDictionary x:Key="Light">
                <Color x:Key="UserAccentColor">#FFFFA500</Color>
                <SolidColorBrush x:Key="UserAccentBrush" Color="{StaticResource UserAccentColor}"/>
            </ResourceDictionary>

更改颜色:

foreach (var dict in App.Current.Resources.ThemeDictionaries)
{
    var theme = dict.Value as Windows.UI.Xaml.ResourceDictionary;
    ((SolidColorBrush)theme["UserAccentBrush"]).Color = color;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接