2017-03-04 73 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; 
}