Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Resource Dictionary Color in the runtime

Tags:

c#

wpf

In XAML:

<ResourceDictionary>
    <Color x:Key="BrushColor1">Red</Color>
    <Color x:Key="BrushColor2">Black</Color>

    <LinearGradientBrush x:Key="GradientBrush1" StartPoint="0,0.5" EndPoint="1,0.5">
        <GradientStop Color="{DynamicResource BrushColor2}" Offset="0" />
        <GradientStop Color="{DynamicResource BrushColor1}" Offset="1" />
    </LinearGradientBrush>
</ResourceDictionary>

In C#:

    public void CreateTestRect()
    {
        Rectangle exampleRectangle = new Rectangle();
        exampleRectangle.Width = 150;
        exampleRectangle.Height = 150;
        exampleRectangle.StrokeThickness = 4;
        exampleRectangle.Margin = new Thickness(350);

        ResourceDictionary resources = this.Resources;
        resources["BrushColor1"] = Colors.Pink;
        resources["BrushColor2"] = Colors.RoyalBlue;
        Brush brush =(Brush)this.FindResource("GradientBrush1");

        exampleRectangle.Fill = brush;
        canvas.Children.Insert(0, exampleRectangle);
    }

How to change those Color elements in the runtime in C#. The LinearGradientBrush should get changed dynamically?

I wish to do something like this:

(Color)(this.FindResource("BrushColor1")) = Colors.Pink;

but I failed.

like image 945
dongx Avatar asked Nov 15 '12 18:11

dongx


2 Answers

You can directly overwrite the value in the resource dictionary.

For example:

ResourceDictionary resources = this.Resources; // If in a Window/UserControl/etc
resources["BrushColor1"] = System.Windows.Media.Colors.Black;

That being said, I would normally recommend not doing this. Instead, I would have two sets of colors, each with their own key, and use some mechanism to switch which color is assigned to your values at runtime instead. This lets you leave the entire logic for this in the xaml itself.

like image 77
Reed Copsey Avatar answered Sep 22 '22 11:09

Reed Copsey


I just solved it. Looks like only LinearGradientBrush does not support DynamicResource for color. Even u overwrite the dynamic color, the LinearGradientBrush itself won't get updated. PS: SolidColorBrush supports runtime color change. Do something below instead:

LinearGradientBrush linearGradientBrush = (LinearGradientBrush)(this.FindResource("GradientBrush1"));
linearGradientBrush.GradientStops[0].Color = color1;
linearGradientBrush.GradientStops[1].Color = color2;

If the LinearGradientBrush is hidden in a nested complex brush defined in Resource Dictionary, you make the LinearGradientBrush emerged, and assign a key to it.

like image 28
dongx Avatar answered Sep 21 '22 11:09

dongx