问题
[UWP]
I have many grids with color binding from 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>
Then I want to change all of its, in code like this
Application.Current.Resources["MyColor"] = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 242, 101, 34));
But it not work. May I miss something? When I navigate to another page and navigate back, above code throw a System.Exception
回答1:
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
回答2:
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.
回答3:
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;
}
回答4:
(App.Current.Resources["MyColor"] as SolidColorBrush).Color = Windows.UI.Color.FromArgb(255, 242, 101, 34);
来源:https://stackoverflow.com/questions/42596564/how-to-change-color-define-in-xaml-resources-in-code-uwp