Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a SolidColorBrush resource's colour at runtime?

Tags:

c#

wpf

xaml

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

like image 804
mbdavis Avatar asked Jan 21 '14 16:01

mbdavis


2 Answers

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.

like image 194
Anatoliy Nikolaev Avatar answered Oct 19 '22 23:10

Anatoliy Nikolaev


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);
like image 45
dkozl Avatar answered Oct 19 '22 22:10

dkozl