How to access and change the values of Resources in Resource Dictionary at runtime in Windows Universal Apps?

放肆的年华 提交于 2019-12-24 23:27:55

问题


I am migrating my Windows Phone 8 App to Windows Universal Apps. I have created a Resource Dictionary with some values in Windows 8.1 project and included its path in App.xaml file. Below is Resource Dictionary and App.xaml.

Resource Dictionary

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp.Styles">

<SolidColorBrush Color="#388941"
                 x:Key="AppBackGroundColor" />
<SolidColorBrush Color="White"
                 x:Key="PageTitleColor" />
<SolidColorBrush Color="White"
                 x:Key="AppFontColor" />
<SolidColorBrush Color="White"
                 x:Key="StatusColor" />
</ResourceDictionary>

App.xaml

<Application
x:Class="MyCouncilServices.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp">

<Application.Resources>
    <!-- Application-specific resources -->
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

            <!-- 
                Styles that define common aspects of the platform look and feel
                Required by Visual Studio project and item templates
             -->
            <ResourceDictionary Source="/Styles/Styles.xaml"/>

        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Now, I want to know how can I access this values in whole App and change its value in c# code.

I tried the same way as I did in Windows Phone 8 project as below but it was causing System.Argument Exception.

if(App.Current.Resources.ContainsKey("AppBackGroundColor"))
  {                      App.Current.Resources.Remove("AppBackGroundColor");
   }             App.Current.Resources.Add("AppBackGroundColor",GetColorFromHex(#FFFFFF));//Getting error at this line.System.ArgumentException ("An item with the same key has already been added.")

I want to use the Resources in my entire app.

Please can anyone suggest how can we access the resources from Dictionary and change its values.


回答1:


You don't have to remove and add, when you can simply overwrite. Just like this:

App.Current.Resources["AppBackGroundColor"] = new SolidColorBrush(Colors.Red); // Red for example

Add this line to OnLaunched() method in App.xaml file at the beginning. I tried this and it works for me.



来源:https://stackoverflow.com/questions/28835394/how-to-access-and-change-the-values-of-resources-in-resource-dictionary-at-runti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!