简体   繁体   English

WPF更改“资源”中的“厚度”对象并在后面的代码中分配

[英]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. 我在Window的资源集合中定义了一个“厚度”资源,该资源在所有方面都设置为值10。 I have 3 Buttons in that window. 我在那个窗口中有3个按钮。

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. 单击第三个按钮后,我将获取该资源的值,将其更改(200个,所有边),然后将其静态应用到第一个按钮,然后将其动态应用到第二个按钮,但仍然为按钮选择旧值(10),即动态使用它。 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). 对于Buttton静态使用它,它应该获取旧值(10),但我认为只是因为第二个按钮是动态获取它,它将反映更改(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. 您确实意识到Thickness是一种值类型,这就是为什么当您更改它的值时,它将不会在资源中受到影响。

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. 这可能会误导。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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