书名:WPF专业编程指南
作者:李应保
出版社:电子工业出版社
出版时间:2010-01
ISBN:9787121100116
一、模板绑定
- (TemplateBinding)
- WPF提供强大的模板功能,本书第10章,将详细介绍WPF模板。模板绑定扩展是用来把原对象中的属性和模板对象中的属性联系起来。请看下面的例子:
<Window x:Class="Yingbao.Chapter2.TemplateBindingEx.AppWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="模板绑定扩展" Height="134" Width="226">
<Window.Resources>
<ControlTemplate TargetType="{x:Type Button}"
x:Key="buttonTemp">
<Border BorderThickness="3" Background
="{TemplateBinding Foreground}">
<TextBlock Name="txtblk" FontStyle ="Italic"
Text="{TemplateBinding Content}"
Foreground="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Window.Resources>
<StackPanel Orientation="Vertical" Height="362" Width="394">
<Button Height="50" Foreground="Red" FontSize="24"
Template="{StaticResource buttonTemp}">按钮1</Button>
<Button Height="50" Foreground="Yellow" FontSize="24"
Template="{StaticResource buttonTemp}">按钮2</Button>
</StackPanel>
</Window>
- 在ControlTemplate中,使用TemplateBinding扩展把TextBlock的前景色设置为控件的背景色。
二、x:Type扩展
- x:Type扩展在XAML中取对象的类型,相当于C#中的typeof操作,这种操作发生在编译时刻,如前面的例子中的:
<ControlTemplate TargetType="{x:Type Button}"
x:Key="buttonTemp">
它等价于下面的C#语句:
ControlTemplate tmplt = new ControlTemplate();
tmplt.TargetType = typeof(Button);
.....
注意:类型名字和命名空间有关。
三、x:Static扩展
- 静态扩展用来把某个对象中的属性或域的值赋给目标对象的相关属性。这个扩展总是而且只有一个参数,这个参数就是源对象的属性。例如:
<TextBlock Name="exText" Background="
{DynamicResource {x:Static
SystemColors.ActiveCaptionBrushKey}}" Height="30"
FontSize="24">清泉石上流
</TextBlock>
{ x:Static SystemColors.ActiveCaptionBrushKey} 静态扩展取的ActiveCaptionBrush值。
四、x:null扩展
- x:null扩展是一种最简单的扩展,其作用就是把目标属性设置为null。
五、x:Array扩展
- Array扩展就是在XAML里创建一个数组。使用Array扩展创建数组很容易,但在词法上和其他XAML扩展不同,它不需要使用大括号"{}",原因在于Array里面含有多个元素。
一个整数数组的例子如下:
<Window x:Class="Yingbao.Chapter2.ArraryEx.AppWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="在XAML中使用数组" Height="151" Width="244">
<Window.Resources>
<x:ArrayExtension Type="{x:Type sys:Int32}"
x:Key="numArray">
<sys:Int32>10</sys:Int32>
<sys:Int32>20</sys:Int32>
<sys:Int32>30</sys:Int32>
<sys:Int32>40</sys:Int32>
</x:ArrayExtension>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{StaticResource numArray}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Width="100"
Height="30" Margin="4"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>