xelor
xelor

Reputation: 319

WPF override key in resource dictionary with C#

I have a wpf-application with a resource dictionary like this:

<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>

But now - at the startup of the application I sometimes want to change the colors.

I tried something like this:

<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();
    }
}

The problem here is that the "Background" is not changed, because it's aready evaluated with the original color.

In the end new color is read from a config file - so I don't know it at compile-time. Do you have any idea how to approach this?

Thank you in advance

Upvotes: 0

Views: 930

Answers (1)

user2250152
user2250152

Reputation: 20823

I suppose that you have your ResourceDictionary referenced in Application.Resources

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

In that case you have to use DynamicResource instead of StaticResource

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

Upvotes: 1

Related Questions