【问题标题】:Is there a simple way to specify int value in xaml有没有一种简单的方法可以在 xaml 中指定 int 值
【发布时间】:2014-01-22 03:01:37
【问题描述】:

我想在 xaml 中使用 int 值设置 Tag 属性。但是在资源中定义 int 然后引用这个资源作为绑定对我来说不是一个完美的方法。将字符串值从代码转换为 int 更容易。 那么,有没有办法在 xaml 中轻松设置 int 值?

【问题讨论】:

    标签: wpf xaml binding


    【解决方案1】:

    请试试这个。

    在 xaml 中添加命名空间 xmlns:sys="clr-namespace:System;assembly=mscorlib"

    <sys:Int16 x:Key="IntNo">1</sys:Int16> or
    
    <sys:Int32 x:Key="IntNo1" >1</sys:Int32>
    

    注意:同样,您也可以使用 Double value

    【讨论】:

      【解决方案2】:

      如果对将其声明为资源不感兴趣,您可以在行内声明它,有点像这样:

          <Button>
              <Button.Tag>
                  <sys:Int32>5</sys:Int32>
              </Button.Tag>
          </Button>
      

      【讨论】:

      • 不幸的是,它的字母也太多了。我需要为 Tag="int:0", Tag="int:1" 等几个元素设置标签
      • Tag 属性的类型为 object。即使您想从后面的代码访问它,您也必须进行类型转换(int)button.Tag。能说说用例吗?
      • 是的,但是 (int)button.Tag 比 int.Parse((string)button.Tag) 更简单 :) 好的,据我所知,使用字符串值来呈现这种外观是最简单的现有方式
      • 是的,XAML 中没有其他方法。或者使用 Resource 对我来说也不错。
      • @Arteny - 对于任何一种方法,您都可以创建一个静态扩展方法来获取标签属性并将其转换为 int。例如。 public static int TagAsInt(this YourBaseElementClass e) { return (int)e.Tag; }。然后使用是微不足道的myElement.TagAsInt()。如果将 Tag 定义为字符串更容易,您只需更改该方法来进行解析,并使用完全相同的方法。
      【解决方案3】:
      xmlns:sys="clr-namespace:System;assembly=mscorlib"
      
      
      <Grid>
          <Grid.Resources>
              <sys:Int32 x:Key="IntValue" >1</sys:Int32>
          </Grid.Resources>
          <Button x:Name="Button" Tag="{StaticResource IntValue}"></Button>
      </Grid>
      

      够简单吗?如果您要在多个地方使用您的值,上述示例将是合适的。否则:

      <Button x:Name="Button" >
              <Button.Tag>
                  <sys:Int32>1</sys:Int32>
              </Button.Tag>
          </Button>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多