【问题标题】:How can I change a style via code that is stored in a resource dictionary in App.xaml on the fly?如何通过存储在 App.xaml 资源字典中的代码动态更改样式?
【发布时间】:2017-06-07 15:57:50
【问题描述】:

我试图让整个应用程序中的几种核心颜色能够由用户动态更改。我目前的想法是有一个 SolidColorBrush 作为我的“主题颜色”,然后在我的主要样式中引用它。

<SolidColorBrush x:Key="ReflectiveColor1" Color="#FF0E777B"></SolidColorBrush>

这个 sn-p 存储在我的 App.xaml 中引用的资源字典中

<Application.Resources>
    <ResourceDictionary Source="DictionaryAlienwareTheme.xaml">
    </ResourceDictionary>
</Application.Resources>

当我尝试访问 App.cs 中的颜色时出现错误

 Application.Current.Resources["ReflectiveColor1"] = Colors.Black;

错误:

System.Runtime.InteropServices.COMException: 'No installed components were 
detected.
Local values are not allowed in resource dictionary with Source set 

有没有办法让这个工作?我假设这个错误是因为它不希望我们修改存储在那里的样式,但我不知道解决方法。

【问题讨论】:

  • 颜色分配也是错误的。您正在尝试将颜色分配给之前的 SolidColorBrush。应该是((SolidColorBrush)Application.Current.Resources["ReflectiveColor1"]).Color = Colors.Black;

标签: xaml uwp


【解决方案1】:

首先,在您的App.xaml 中,如果您想引用您自己定义的DictionaryAlienwareTheme.xaml,您需要按照@AVK 所说的将字典合并到当前应用程序。更多详情请参考this article的“合并资源字典”部分。

其次,使用合并资源后,如果要更新后面的主题资源代码,可能需要使用Application.Current.Resources.MergedDictionaries来访问合并字典,而不是Application.Current.Resources。例如,

public MainPage()
{
   this.InitializeComponent(); 
   var mergedDict = Application.Current.Resources.MergedDictionaries.FirstOrDefault();
   ((SolidColorBrush)mergedDict["ReflectiveColor1"]).Color = Colors.Red;
}

顺便说一下,上面的代码sn-p显示,ReflectiveColor1是SolidColorBrush你不能直接设置颜色。

【讨论】:

  • 我已经完全按照您的要求完成了,但仍然收到错误消息 - “System.Runtime.InteropServices.COMException: '未检测到已安装的组件。资源字典中不允许使用本地值与源集[行:0 位置:0]'"
【解决方案2】:

在您将所有资源字典合并在一起之前,应用程序将无法找到资源ReflectiveColor1。

更改您的App.xaml 以合并字典。如下所示。

<Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DictionaryAlienwareTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

那么您应该能够以与之前相同的方式访问资源。

【讨论】:

  • 这似乎并不完全有效,虽然它更接近。在其他 XAML 中,您将如何引用 ReflectiveColor1?我试过 Binding 和 ThemeResource 但它们似乎没有更新为代码中选择的颜色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
相关资源
最近更新 更多