How to change Color define in Xaml Resources in code (UWP)

故事扮演 提交于 2019-12-05 23:41:14

StaticResource and ThemeResource doesn't support dynamic change as you try like DynamicResource in WPF. BTW if you reload the view like navigating back and forward you can see the changes but this is not a good solution.

Other hand, you can achieve some dynamic change with ThemeResource and change eg. colors depend on the current theme (Dark, Light, High Contrast)

Futher reading: https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/xaml-theme-resources

If you know it's a SolidColorBrush then modify the Color property directly.

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

You can't change the resources, but you can modify their properties if you have access.

I did it in the following way:

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>

Change color:

foreach (var dict in App.Current.Resources.ThemeDictionaries)
{
    var theme = dict.Value as Windows.UI.Xaml.ResourceDictionary;
    ((SolidColorBrush)theme["UserAccentBrush"]).Color = color;
}
Ritesh Patel
(App.Current.Resources["MyColor"] as SolidColorBrush).Color = Windows.UI.Color.FromArgb(255, 242, 101, 34);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!