标记扩展
名称 | 说明 |
---|---|
x:Type | 声明数据类型,比如自定义一些按钮/组件 |
x:Null | 表示空值。如果一个属性具有默认值但不想用那个值,就要显式设置null |
x:Array | 传递一个已知类型的ArrayList实例(例子是前端自己展示数据) |
x:Static | 访问c#类中static成员(变量和函数)如果一个程序需要国际化支持,此时将需要显示的字符串存在一个资源类的static属性中,那么会多次使用x:Static |
x:Type示例
新建一个MyWindow.xaml作为子窗口,内容如下
MyWindow.xaml.cs
自定义了一个button的子类,带一个Type类型的属性UserWindowType。这个类还重写了OnClick,如果属性UserWindowType是Window(及其子类),那就要展示出来。
MainWindow.xaml
因为MyButton和MyWindow都是命名空间pxy中的,所以要加前缀local映射。现在用x:Type说明UserWindowType就是MyWindow类型的,而MyWindow是Window的派生类,所以就要展示出来了。
MainWindow.xaml.cs
最终实现的效果是点击主窗口的Show按钮,弹出另一个窗口:
x:Null示例
<Window.Resources>
<Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
<Setter Property="Width" Value="60"/>
<Setter Property="Height" Value="36"/>
<Setter Property="Margin" Value="5"/>
</Style>
</Window.Resources>
<StackPanel>
<Button />
<Button />
<Button Style="{x:Null}"/>
</StackPanel>
< Style >把所有Button设置成一种格式了(Margin表示四周5个像素的留白),对于最后一个,则按照默认格式来,效果:
x:Array示例
<Window x:Class="pxy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:pxy"
mc:Ignorable="d"
Title="MainWindow" Height="170" Width="200">
<Grid Background="LightBlue">
<ListBox Margin="5">
<ListBox.ItemsSource>
<x:Array Type="sys:String">
<sys:String>AA</sys:String>
<sys:String>BB</sys:String>
<sys:String>CC</sys:String>
</x:Array>
</ListBox.ItemsSource>
</ListBox>
</Grid>
</Window>
在解析<x:Array>标签时,编译器会产生调用AddChild方法的代码把< x:Array >的子元素逐个添加到x:Array的实例Items里。效果:
x:Static示例
为MainWindow类添加static成员。
MainWindow.xaml.cs
namespace pxy
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public static string WindowTitle = "我是窗口";
public static string ShowText { get { return "你好!"; } }
public MainWindow()
{
InitializeComponent();
}
}
}
MainWindow.xaml:Title使用静态成员变量,TextBox的内容使用静态成员函数的返回值。
<Window x:Class="pxy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:pxy"
mc:Ignorable="d"
Title="{x:Static local:MainWindow.WindowTitle}" Height="170" Width="200">
<Grid Background="LightBlue">
<TextBox FontSize="45" Text="{x:Static local:MainWindow.ShowText}"/>
</Grid>
</Window>
指令元素
x:Code 包含一些c#代码
x:XData 数据提供者标签下存放数据的标签
数据源:包含数据的对象
数据提供者:把数据源中的数据提供给数据使用者