mbdavis
mbdavis

Reputation: 4010

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

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

Upvotes: 5

Views: 5442

Answers (2)

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

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.

Upvotes: 6

dkozl
dkozl

Reputation: 33364

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

Upvotes: 4

Related Questions