简体   繁体   中英

WPF Change Thickness object in Resource and assign in code behind

I have defined one Thickness resource in Window's resources collection which is set to value 10 along all sides. I have 3 Buttons in that window.

Upon clicking the third button, I am fetching the value of that resource, changing it(200, all edges) and applying it statically for first button and dynamically for second but still it's picking up the old value(10) for the button which is using it dynamically. For Buttton using it statically it was supposed to fetch the old value (10) but I thought just because the second button is fetching it dynamically, it will reflect the change(200).

<Window x:Class="WpfApplicationUnleashed.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:WpfApplicationUnleashed"
        Title="Window1" >


    <Window.Resources>
        <Thickness x:Key="BadiThickness">10</Thickness>
    </Window.Resources>

    <StackPanel>
        <Button x:Name="cmdStatic" HorizontalAlignment="Center" >
            I am Static
        </Button

        <Button x:Name="cmdDynamic" HorizontalAlignment="Center" >
            I am Dynamic 
        </Button>

        <Button x:Name="cmdChanger" HorizontalAlignment="Center" Click="cmdChanger_Click">
 I am Changer
        </Button>
    </StackPanel>
</Window>

Code:

private void cmdChanger_Click(object sender, RoutedEventArgs e)
{
    Thickness th = (Thickness)this.FindResource("BadiThickness");
    th.Bottom = 200;
    th.Top = 200;
    th.Left = 200;
    th.Right = 200;

    cmdDynamic.SetResourceReference(Button.MarginProperty, "BadiThickness");
    cmdStatic.Margin = (Thickness)this.FindResource("BadiThickness");
}

You do realize that Thickness is a value type and that is why when you change it's value, it won't be affected in the resource.

What you can do to set that resource's value is following:

this.Resource["BadiThickness"] = new Thickness(200);

On a side note, please avoid using Hindi in a resource's name. That may mislead.

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