如何在XAML中定义变量?

Edw*_*uay 50 variables wpf xaml

我在XAML中有以下两个按钮:

<Button Content="Previous"
        Margin="10,0,0,10"/>
<Button Content="Next"
        Margin="0,0,10,10"/>
Run Code Online (Sandbox Code Playgroud)

如何将"10"定义为变量,以便我可以在一个地方更改它,如下所示:

PSEUDO代码:

<variable x:key="theMargin"/>
<Button Content="Previous"
        Margin="{Variable theMargin},0,0,{Variable theMargin}"/>
<Button Content="Next"
        Margin="0,0,{Variable theMargin},{Variable theMargin}"/>
Run Code Online (Sandbox Code Playgroud)

Sor*_*oot 87

试试这个:

添加到xamlfile的头部

xmlns:System="clr-namespace:System;assembly=mscorlib"
Run Code Online (Sandbox Code Playgroud)

然后将其添加到资源部分:

<System:Double x:Key="theMargin">2.35</System:Double>
Run Code Online (Sandbox Code Playgroud)

最后,在边距上使用厚度:

<Button Content="Next">
   <Button.Margin>
      <Thickness Top="{StaticResource theMargin}" Left="0" Right="0"
                  Bottom ="{StaticResource theMargin}" />
   </Button.Margin>
</Button>
Run Code Online (Sandbox Code Playgroud)

可以用这种方式定义很多系统类型:int,char,string,DateTime等

注意:你是对的...必须做一些更好的测试..改为代码,以便它应该工作

  • 嗯,我在 Window.Resources 中添加了 &lt;System:Double x:Key="theMargin"&gt;2.35&lt;/System:Double&gt; 并得到了“System:Double was not found”,添加了“System”作为参考但没有帮助,我错过了什么? (2认同)
  • 我发现了我的问题:我正在添加这个xmlns:System ="clr-namespace:Microsoft.Win32; assembly = mscorlib"并且应该添加这个:xmlns:System ="clr-namespace:System; assembly = mscorlib" (2认同)

Cod*_*dyF 7

类似于 Sorskoot 的回答,您可以添加要使用的厚度资源,从而独立定义每个边距方向

<UserControl.Resources>
    <Thickness x:Key="myMargin" Top="5" Left="10" Right="10" Bottom ="5"></Thickness>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

然后只需使用厚度作为边距:

<Button Content="Next" Margin="{StaticResource myMargin}"/>
Run Code Online (Sandbox Code Playgroud)