问题描述
<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.Resources
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="YourDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
在这种情况下,您必须使用 DynamicResource
而不是 StaticResource
<SolidColorBrush x:Key="Background" Color="{DynamicResource Primary500}"/>