简体   繁体   中英

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;

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM