XAML是一种相对简单,通用的声明式编程语言,适用于构建和初始化.NET对象。
XAML规范了一些规则,用于把.NET命名空间,类型,属性,事件映射为XML命名空间,元素,特性。
元素和特性
对象元素:XAML中定义一个XML元素(等同于.NET中用默认构函实例化一对象)
特性:设置对象元素的一个属性(等同于设置实例对象的同名属性)
命名空间
<!-- xmlns中内容及为一命名空间 -->
<!-- 主命名空间,映射了.NET,System下多个命名空间 -->
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK" />
<!-- 次命名空间定义,需要前缀 -->
<MyNamespace:Button xmlns:MyNamespace="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK"/>
属性元素
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<!-- 使用属性元素(该元素没有自己的特性),元素对象.特性名 -->
<Button.Content>
<!-- 可包含另一元素对象 -->
<Rectangle Height="40" Width="50" Fill="Black"/>
</Button.Content>
<Button.Background>
Red
</Button.Background>
</Button>
等同于C#代码:
System.Windows.Shape.Rectangle r = new System.Windows.Shape.Rectangle();
r.Width = 40;
r.Height = 50;
r.Fill = System.Windows.Media.Brushes.Black;
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Content = r;
b.Background = System.Windows.Media.Brushes.Red;
类型转换器
上例中的Red就是通过XAML类型转换器将一字串表达式转换为想要数据类型的。
标记扩展
特性值由{}括起来,XAML编译器或解析器就把它当标记扩展值,而非普通字符串。
<Button xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="{x:Null}" Height="{x:Static SystemParameters.IconHeight}" Width="{x:Static SystemParameters.IconWidth}" Content="{Binding Path=Height, RelativeSource={RelativeSource Self}}"> </Button>
对象元素的子元素XAML文件向所有XML文件一样,必须有一单独跟对象元素。
1.内容属性
用于设置XML元素中任何内容,比如:Button的Content特性,ComboBox的Items特性等
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">按钮内容</Button>
2.集合项XAML允许将项添加到支持索引的2种类型集合中:IList和Dictionary
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <ListBox.Items> <ListBoxItem Content="Item_1"/> <ListBoxItem Content="Item_2"/> </ListBox.Items> </ListBox>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Color x:Key="1" A="255" R="255" G="255" B="255"/> </ResourceDictionary>
注:带有x:key的XAML中指定值总是作为字符串处理,除非使用标记扩展。
编译:将XAML与过程式代码混合使用
1.在运行时加载和解析XAML
WPF的运行时XAML解析器公开为2个类,都位于System.Windows.Markup中:XamlReader和XamlWriter
2.命名XAML元素
<Button x:Name="MyButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 按钮 </Button>
编译XAML包括3件事:1.XAML文件转换为特殊二进制格式
2.转换好的二进制资源嵌入正在被创建的程序集
3.将XAML和后台代码自动关联(XAML根元素用x:class指定一子类)
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyNamespace.MyWindow"> </Window>