如何在 Windows 通用应用程序中在运行时访问和更改资源字典中资源的值?
我正在将我的 Windows Phone 8 应用程序迁移到 Windows 通用应用程序.我在 Windows 8.1 项目中创建了一个具有一些值的资源字典,并将其路径包含在 App.xaml 文件中.下面是资源字典和App.xaml.
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.
资源字典
<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>
应用程序.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>
现在,我想知道如何在整个应用程序中访问这些值并在 c# 代码中更改其值.
Now, I want to know how can I access this values in whole App and change its value in c# code.
我尝试了与我在 Windows Phone 8 项目中所做的相同的方法,如下所示,但它导致了 System.Argument 异常.
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.
请谁能建议我们如何从 Dictionary 访问资源并更改其值.
Please can anyone suggest how can we access the resources from Dictionary and change its values.
无需删除和添加,只需覆盖即可.就像这样:
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
将此行添加到 App.xaml 文件中的 OnLaunched()
方法开头.我试过了,它对我有用.
Add this line to OnLaunched()
method in App.xaml file at the beginning. I tried this and it works for me.