我想在XAML中设置标签属性为整数值。但是,在资源中定义整数,然后将该资源作为绑定引用似乎不是一种完美的方式。更简单的方法是从代码中将字符串值转换为整数。 因此,有没有一些简单的方法来在XAML中设置整数值呢?
请尝试这个。
在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>
注意:同样的方法也适用于双精度值。如果不想将它声明为资源,您可以像这样在行内声明:
<Button>
<Button.Tag>
<sys:Int32>5</sys:Int32>
</Button.Tag>
</Button>
Tag="int:0"
,Tag="int:1"
等等。 - artenyTag
属性是 object
类型。即使您想从代码后台访问它,也必须进行类型转换 (int)button.Tag
。您能说出其使用情况吗? - Rohit Vatspublic static int TagAsInt(this YourBaseElementClass e) { return (int)e.Tag; }
。然后使用非常简单,只需调用 myElement.TagAsInt()
即可。如果将Tag定义为字符串更容易,您只需更改该方法以执行解析,并完全相同地使用它。 - ToolmakerStevexmlns: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>
<Window
x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Button x:Name="MyButton" Click="MyButton_Click" Content="Print 'Tag' value to console">
<Button.Tag>
<x:Int32>42</x:Int32>
</Button.Tag>
</Button>
</Grid>
</Window>
后台代码:
private void MyButton_Click(object sender, RoutedEventArgs e)
{
int value = (int) MyButton.Tag;
Debug.WriteLine(value);
}
int
的命令参数,方法如下:<Button Command="{x:Bind ViewModel.AddMinutesCommand}" Content="+ 30 Minutes">
<Button.CommandParameter>
<x:Int32>30</x:Int32>
</Button.CommandParameter>
</Button>
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
就可以为x
命名空间指定而不必在此处指定2009/xaml
之类的内容。