ek07
ek07

Reputation: 1

c# XAML thickness resource not working

I'm getting some issues with the code below, the compiler doesn't display any errors and the program runs correctly but while the color changes the thickness doesn't.
What's wrong?
I suppose something related to the c# codebehind because if I manually change the value of the thickness resource while the app is running(the new version of vs2017 allows me to do that) everything works fine.

xaml

...
<Page.Resources>
    <SolidColorBrush x:Key= "myColor" Color="Red"/>
    <Thickness x:Key="myThickness">1,1,1,1</Thickness>
<Page.Resources>
...
<Broder BorderBrush="{StaticResource myColor}" BorderThickness="{StaticResource myThickness}">something</Border>
...

c#

Thickness myThicknessVar= (Thickness)this.Resources["myThickness"];
myThicknessVar= new Thickness(5, 5, 5, 5);

SolidColorBrush myColorVar= (SolidColorBrush)this.Resources["myColor"];
myColorVar.Color = Colors.Green;

Upvotes: 0

Views: 300

Answers (1)

Vladimir Khavulya
Vladimir Khavulya

Reputation: 91

The reason that this works:

SolidColorBrush myColorVar = (SolidColorBrush)this.Resources["myColor"];
myColorVar.Color = Colors.Green;

Is that you are modifying an existing object that you have retrieved from the resource dictionary - myColorVar. Variable myColorVar is a reference to this.Resources["myColor"].

When you are doing this:

Thickness myThicknessVar = (Thickness)this.Resources["myThickness"];
myThicknessVar = new Thickness(5, 5, 5, 5);

You are assigning a new value to variable "myThicknessVar", without changing the actual value that is in the resource dictionary.

To attain the desired behavior you need to do two things:

  1. Change the object stored in the resource dictionary:
this.Resources["myThickness"] = new Thickness(5, 5, 5, 5);
  1. Use DynamicResource in XAML instead of StaticResource:
<Border BorderBrush="{StaticResource myColor}" BorderThickness="{DynamicResource myThickness}">
    <!-- something -->
</Border>

Upvotes: 1

Related Questions