所谓的标记扩展,实际上是一种特殊的Attribute=value语法,其特殊的地方在于Value字符串是由一对花括号及其括起来的内容组成,XAML编译器会对这样的内容作出解析、生成相应的对象。
例如:当Slider的滑块滑动时TextBox就会显示Slider当前的值。
<Window x:Class="Chapter3.Page24.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBox Text="{Binding ElementName=sl,Path=Value,Mode=TwoWay}" Margin="5"/>
<Slider x:Name="sl" Margin="5"/>
</StackPanel>
</Window>
这里的
Text="{Binding ElementName=sl,Path=Value,Mode=TwoWay}"
就是标记扩展。
分析这段代码:
1) 当编译器看到这句代码时就会把花括号里的内容解析成相应的对象。
2) 对象的数据类型是紧邻左花括号的字符串。
3) 对象的属性是由一串以逗号连接子字符串负责初始化(注意,属性值不在加引号)。
最后,使用标记扩展时还需要注意以下几点:
1) 标记扩展是可以嵌套的,例如
Text="{Binding Source={StaticResource myDataSource}, Path={PersonName}"
是正确的语法。
2) 标记扩展具有一些简写语法,例如“{Binding Value, ...}”与{Binding Path=Value, ...}是等价的,{StaticResource myString, ...} 与 {StaticResource ResourceKey=myString, ...} 是等价的。
3) 标记扩展的类名均可以以单词Extension为后缀,在XAML使用他们的时候Extension后缀可以省略不写,比如写 Text="{x:Static}"与写 Text="{x:StaticExtension}"是等价的。