【问题标题】:How can I define a variable in XAML?如何在 XAML 中定义变量?
【发布时间】:2009-05-18 11:42:37
【问题描述】:

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

<Button Content="Previous"
        Margin="10,0,0,10"/>
<Button Content="Next"
        Margin="0,0,10,10"/>

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

伪代码:

<variable x:key="theMargin"/>
<Button Content="Previous"
        Margin="{Variable theMargin},0,0,{Variable theMargin}"/>
<Button Content="Next"
        Margin="0,0,{Variable theMargin},{Variable theMargin}"/>

【问题讨论】:

    标签: wpf xaml variables


    【解决方案1】:

    试试这个:

    添加到 xamlfile 的头部

    xmlns:System="clr-namespace:System;assembly=mscorlib"
    

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

    <System:Double x:Key="theMargin">2.35</System:Double>
    

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

    <Button Content="Next">
       <Button.Margin>
          <Thickness Top="{StaticResource theMargin}" Left="0" Right="0"
                      Bottom ="{StaticResource theMargin}" />
       </Button.Margin>
    </Button>
    

    很多系统类型都可以这样定义:int、char、string、DateTime等

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

    【讨论】:

    • hmmm,我在 Window.Resources 中添加 2.35 并得到“System:Double was not found”,添加了“System”作为参考但没有帮助,我错过了什么?
    • Double 不会出现在下拉列表中,只有例如“RegistryHive”和其他三个,我引用了 System.Core,还有什么要引用的?
    • 我发现了我的问题:我正在添加这个 xmlns:System="clr-namespace:Microsoft.Win32;assembly=mscorlib" 并且应该添加这个:xmlns:System="clr-namespace: System;assembly=mscorlib"
    • 在我看来,这更像是一个常数而不是一个变量。硬编码值对我没有多大作用。
    • 我必须为System 使用小写的's' 才能完成这项工作。
    【解决方案2】:

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

    <UserControl.Resources>
        <Thickness x:Key="myMargin" Top="5" Left="10" Right="10" Bottom ="5"></Thickness>
    </UserControl.Resources>
    

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

    <Button Content="Next" Margin="{StaticResource myMargin}"/>
    

    【讨论】:

      【解决方案3】:

      为什么不尝试将值添加为StaticResource

      Resources.Add("theMargin", 10);
      

      然后你可以像这样得到那个值:

      <Button Content="Previous"
              Margin="{StaticResource theMargin},0,0,{StaticResource theMargin}"/>
      <Button Content="Next"
              Margin="0,0,{StaticResource theMargin},{StaticResource theMargin}"/>
      

      【讨论】:

      • 我添加了 Resources.Add("theMargin", 50);在我的代码后面的 InitializeComponent 之后,但 XAML 无法访问它。
      • 在 MarkupExtension 表达式的结束 '}' 之后不允许出现文本 ',0,0,{StaticResource theMargin}'
      【解决方案4】:

      你需要在 InitializeComponent 之前调用它,或者之后使用 INotifyPropertyChanged 接口

      【讨论】:

        【解决方案5】:

        在 .NET Core 中,@Sorskoot 的回答有效,但产生了警告。所以我使用了这个命名空间声明:

        xmlns:system="clr-namespace:System;assembly=System.Runtime"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 2016-02-29
          • 1970-01-01
          • 1970-01-01
          • 2020-09-26
          • 2012-10-30
          • 2020-11-27
          相关资源
          最近更新 更多