1.什么是标记扩展?为什么要有标记扩展?
标记扩展是扩展xmal的表达能力
为了克服现存的类型转换机制存在的
常用的标记扩展有如下:
x:Array 代表一个.net数组,它的子元素都是数组元素.它必须和x:Type一起使用,用于定义数组类型
x:null 表示空引用
x:static 在过程式代码中定义的任何一个静态属性、常量和枚举
x:type 表示system.Type的一个实例,就像C#中的typeof
注:标记扩展是有Extension的,可以省略不写
标记扩展的语法是 Attribute={} 是花括号
1.staticExtension
<StackPanel Background="{x:Static Brushes.AliceBlue}" />
2.ArrayExtension StaticResourceExtension
<Window.Resources>
<x:ArrayExtension x:Key="listitemboxs" Type="TextBlock"> <TextBlock Text=" one"></TextBlock> <TextBlock Text=" two"></TextBlock> <TextBlock Text=" three"></TextBlock> </x:ArrayExtension></Window.Resources><StackPanel> <ListBox ItemsSource="{ StaticResourceExtension listitemboxs}"></ListBox></StackPanel>或
<Window x:Class="WpfApplication1.Window3"
xmlns="" xmlns:x="" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="Window3" Height="300" Width="300" WindowStartupLocation="CenterScreen"> <Window.Resources> <sys:String x:Key="stringHell0">Hello WPF</sys:String> </Window.Resources> <Grid> <TextBlock Height="24" Width="100" Text="{ StaticResource ResourceKey=stringHell0}"></TextBlock> </Grid></Window>
3.NullExtension
<StackPanel Background="{x:NullExtension}"/>
4.标记扩展有2种使用方式
<StackPanel Background="{x:NullExtension}"/>
<StackPanel>
<StackPanel.Background> <x:Static Member="Brushes.AliceBlue"></x:Static> </StackPanel.Background> </StackPanel>以上两种方式显示得到一样的效果,但他们的内部实现机制是不一样的
第一种:
- StaticExtension staticExtension = new StaticExtension("Brushes.AliceBlue");
- StackPanel stackPanel = new StackPanel();
- stackPanel.Background = staticExtension.ProvideValue(serviceProvider) as Brush;
- AddChild(stackPanel);
第二种:
- StaticExtension staticExtension = new StaticExtension();
- staticExtension.Member = "Brushes.AliceBlue";
- StackPanel stackPanel = new StackPanel();
- stackPanel.Background = staticExtension.ProvideValue(serviceProvider) as Brush;
- AddChild(stackPanel);
这两种使用方式是一样的。但它们的内部实现机制却不同,Xaml解析器解析成的伪代码分别为:
第一种:
- StaticExtension staticExtension = new StaticExtension("Brushes.AliceBlue");
- StackPanel stackPanel = new StackPanel();
- stackPanel.Background = staticExtension.ProvideValue(serviceProvider) as Brush;
- AddChild(stackPanel);
第二种:
- StaticExtension staticExtension = new StaticExtension();
- staticExtension.Member = "Brushes.AliceBlue";
- StackPanel stackPanel = new StackPanel();
- stackPanel.Background = staticExtension.ProvideValue(serviceProvider) as Brush;
- AddChild(stackPanel);
实战 :拖动slider,textblock里的值变化
<Grid Margin="4">
<Grid.RowDefinitions> <RowDefinition Height="24"></RowDefinition> <RowDefinition Height="4"></RowDefinition> <RowDefinition Height="24"></RowDefinition> </Grid.RowDefinitions>总共有3行row <TextBlock x:Name="tb" Background="White" Text="{Binding ElementName=sid,Path=Value}"></TextBlock> <Slider Name="sid" Grid.Row="2" Value="50" Maximum="100" Minimum="0"></Slider>这里的Grid.Rows是指显示在Grid里的第2行 </Grid>注:绿色表示没看明白,日后要修改注的