如何在Windows通用应用程序的运行时访问和更改资源字典中资源的值

本文关键字:资源 字典 访问 运行时 Windows 应用程序 | 更新日期: 2024-09-24 23:48:17

我正在将我的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>

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>

现在,我想知道如何在整个应用程序中访问这些值,并在c#代码中更改其值。

我尝试了和下面的WindowsPhone8项目中相同的方法,但它导致了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.")

我想在我的整个应用程序中使用资源。

请任何人建议我们如何访问Dictionary中的资源并更改其值。

如何在Windows通用应用程序的运行时访问和更改资源字典中资源的值

当您可以简单地覆盖时,您不必删除和添加。就像这样:

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

将此行添加到App.xaml文件开头的OnLaunched()方法中。我试过这个,它对我有效。