2017-03-04 57 views
1

[UWP]如何改变颜色在XAML资源定义代码(UWP)

我有很多的颜色从电网的App.xaml

MainPage.xaml中......

​​ 结合

的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

+0

你是什么意思,这是行不通的?它是否会抛出异常,Grid的背景颜色是否无法更改? –

+0

颜色不变。没有例外 – HelloWindowsPhone

+0

当我导航到另一个页面,然后导航回上面的代码抛出一个System.Exception – HelloWindowsPhone

回答

1

StaticResourceThemeResource不支持动态更改,因为您尝试在WPF中尝试像DynamicResource。顺便说一句,如果你重新加载视图像前后导航,你可以看到变化,但这不是一个好的解决方案。

另一方面,你可以通过ThemeResource实现一些动态变化,例如改变。颜色取决于当前的主题(黑暗,明亮,高对比度)

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

+0

但我看到Store上的一些应用程序可以做到这一点。用户选择颜色后立即改变颜色(例如:Windows 10商店的Awesome Tube) – HelloWindowsPhone

+1

他们很可能是用绑定来做的,而不是像你所做的那样在代码中做的。 –

0

如果你知道这是一个SolidColorBrush然后直接修改颜色属性。

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; 
}