【问题标题】:WPF override key in resource dictionary with C#WPF用C#覆盖资源字典中的键
【发布时间】:2023-03-07 09:11:01
【问题描述】:

我有一个带有如下资源字典的 wpf 应用程序:

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

  <Color x:Key="Primary200">#FFE6FDF9</Color>
  <Color x:Key="Primary500">#FF00E6BE</Color>
  <Color x:Key="Primary700">#FF01987F</Color>

  <SolidColorBrush x:Key="Background" Color="{StaticResource Primary500}"/>
</ResourceDictionary>

但现在 - 在应用程序启动时,我有时想更改颜色。

我尝试过这样的事情:

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

  <Application.Resources>
      <ResourceDictionary Source="pack://application:,,,/ResourceTest;component/Colors.xaml"/>
  </Application.Resources>
</Application>


public partial class App 
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        Resources.Remove("Primary500");
        Resources.Add("Primary500", Colors.Red);

        var mainWindow = new MainWindow();
        mainWindow.Show();
    }
}

这里的问题是“背景”没有改变,因为它是用原始颜色评估的。

最后,新颜色是从配置文件中读取的——所以我在编译时不知道。 你知道如何解决这个问题吗?

提前谢谢你

【问题讨论】:

  • ResourceDictionary 是附加到您的Application 的那个,还是合并的一个单独的?不管怎样,试试{DynamicResource ...}
  • 是的,它已附加到应用程序中

标签: c# wpf colors config resourcedictionary


【解决方案1】:

我想你在Application.Resources 中引用了你的ResourceDictionary

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

在这种情况下,您必须使用 DynamicResource 而不是 StaticResource

<SolidColorBrush x:Key="Background" Color="{DynamicResource Primary500}"/>

【讨论】:

  • 好主意!我知道由于性能损失,在 UserControls 中使用 DynamicResource 是“危险的”。在资源字典中使用动态资源是否有类似的问题?
猜你喜欢
  • 1970-01-01
  • 2013-10-07
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
相关资源
最近更新 更多