主要参考: http://www.cnblogs.com/zhouyinhui/archive/2007/03/28/690993.html
与Style不同,Style只能改变控件的已有属性值(比如颜色字体)来定制控件,但控件模板可以改变控件的内部结构(VisualTree,视觉树)来完成更为复杂的定制。比如我们可以定制这样的按钮:在它的左办部分显示一个小图标而它的右半部分显示文本。
- 声明一个ControlTemplate对象,做相应的配置,然后将该ControlTemplate对象赋值给控件的Template属性就可以了。
- ControlTemplate包含两个重要的属性:
-
- VisualTree,该模板的视觉树,其实我们就是使用这个属性来描述控件的外观的
- Triggers,触发器列表,里面包含一些触发器Trigger,我们可以定制这个触发器列表来使控件对外界的刺激发生反应,比如鼠标经过时文本变成粗体等。
- 控件(Button)的一些属性,比如高度、宽度、文本等如何在新定义的外观中表现出来呢? 我们使用TemplateBinding 将控件的属性与新外观中的元素的属性关联起来Width="定义了触发器
代码:
<Window x:Class="WpfBook.ImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ImageButton" Height="300" Width="300">
<Window.Resources>
<ControlTemplate x:Key="ImageButton" TargetType="Button">
<Grid>
<Ellipse Width="{TemplateBinding Button.Width}" Height="{TemplateBinding Control.Height}" Fill="{TemplateBinding Button.Background}"/>
<TextBlock Margin="{TemplateBinding Button.Padding}" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{TemplateBinding Button.Content}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsMouseOver" Value="true">
<Setter Property="Button.Foreground" Value="Red" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Template="{StaticResource ImageButton}">abcde</Button>
<Button>def</Button>
</StackPanel>
</Window>