簡體   English   中英

WPF更改“資源”中的“厚度”對象並在后面的代碼中分配

[英]WPF Change Thickness object in Resource and assign in code behind

我在Window的資源集合中定義了一個“厚度”資源,該資源在所有方面都設置為值10。 我在那個窗口中有3個按鈕。

單擊第三個按鈕后,我將獲取該資源的值,將其更改(200個,所有邊),然后將其靜態應用到第一個按鈕,然后將其動態應用到第二個按鈕,但仍然為按鈕選擇舊值(10),即動態使用它。 對於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>

碼:

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");
}

您確實意識到Thickness是一種值類型,這就是為什么當您更改它的值時,它將不會在資源中受到影響。

您可以執行以下操作來設置該資源的值:

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

另外,請避免在資源名稱中使用北印度語。 這可能會誤導。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM