How can I change a colour in a resource dictionary being used in another resource dictionary at runtime?
Here's my setup:
Colours.xaml:
<SolidColorBrush x:Key="themeColour" Color="#16A8EC"/>
Styles.xaml:
<Style x:Key="titleBar" TargetType="Grid">
<Setter Property="Background" Value="{DynamicResource themeColour}"/>
</Style>
Window.xaml
.....
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="res/Styles.xaml"/>
<ResourceDictionary Source="res/Colours.xaml"/>
</ResourceDictionary.MergedDictionaries>
.....
<Grid Style="{DynamicResource titleBar}"></Grid>
Code behind:
Application.Current.Resources["themeColour"] = new SolidColorBrush(newColour);
When the code runs the colour of the grid doesn't change. I don't think Application.Current.Resources["themeColour"] is referring to my solidcolorbrush resource as when if I try to access it before assigning it a new colour, I get a null object reference exception.
So, how should I access the resource "themeColour"?
In order to your code to work, ResourceDictionary must be in a file App.xaml where ResourceDictionary should be:
App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary/StyleDictionary.xaml"/>
<ResourceDictionary Source="Dictionary/ColorDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Code-behind
private void Window_ContentRendered(object sender, EventArgs e)
{
SolidColorBrush MyBrush = Brushes.Black;
Application.Current.Resources["themeColour"] = MyBrush;
}
Why is it better to use App.xaml
correctly all styles and resource dictionaries stored in this file because it was created specifically for this - to all application resources were available from one place. It can also affect application performance in a good way.
there have been cases where a StaticResource has been used successfully, but not DynamicResource (resources are placed in the Window.Resources). But after moving the resource in App.xaml, everything started to work.
It's because your resources are available in Window and not in Application. Try this in Window.xaml.cs:
this.Resources["themeColour"] = new SolidColorBrush(newColour);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With