Kin*_*sar 1 c# win-universal-app
我正在将 Windows Phone 8 应用程序迁移到 Windows 通用应用程序。我创建了一个资源字典,其中包含 Windows 8.1 项目中的一些值,并将其路径包含在App.xaml文件中。下面是资源字典和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>
Run Code Online (Sandbox Code Playgroud)
应用程序.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>
Run Code Online (Sandbox Code Playgroud)
现在,我想知道如何在整个应用程序中访问此值并在 C# 代码中更改其值。
我尝试了与 Windows Phone 8 项目中相同的方法,如下所示,但它导致了 System.Argument 异常。
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.")
Run Code Online (Sandbox Code Playgroud)
我想在我的整个应用程序中使用资源。
请任何人建议我们如何访问词典中的资源并更改其值。
当您可以简单地覆盖时,您不必删除和添加。像这样:
App.Current.Resources["AppBackGroundColor"] = new SolidColorBrush(Colors.Red); // Red for example
Run Code Online (Sandbox Code Playgroud)
将此行添加到App.xaml文件开头OnLaunched()的方法中。我尝试过这个,它对我有用。