WPF学习(10)模板
在前面一篇我们粗略说了Style和Behaviors,如果要自定义一个个性十足的控件,仅仅用Style和Behaviors是不行的,Style和Behaviors只能通过控件的既有属性来简单改变外观,还需要有ControlTemplate来彻底定制,这是改变Control的呈现,也可以通过DataTemplate来改变Data的呈现,对于ItemsControl,还可以通过ItemsPanelTemplate来改变Items容器的呈现。
1.模板
WPF模板有三种:ControlTemplate、DataTemplate和ItemsPanelTemplate,它们都继承自FrameworkTemplate抽象类。在这个抽象类中有一个FrameworkElementFactory类型的VisualTree变量,通过该变量可以设置或者获取模板的根节点,包含了你想要的外观元素树。
先来看下ControlTemplate的例子:
<Window x:Class="TemplateDemo.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">
<Window.Resources>
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
<Grid>
<Ellipse Width="100" Height="100">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Cyan" />
<GradientStop Offset="1" Color="LightCyan" />
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Width="80" Height="80">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Yellow" />
<GradientStop Offset="1" Color="Transparent" />
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Button Content="Hi,WPF" Template="{StaticResource buttonTemplate}" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
这里是将ControlTemplate作为资源的方式共享的,当然也可以通过Style的Setter来设置Button的Template属性来做。
效果如下:

在该ControlTemplate的VisualTree中,Button是被作为TemplatedParent的,这个属性定义在FrameworkElement和FrameworkContentElement中。关于TemplatedParent的介绍,这里可以看Mgen这篇文章。
这里完成了一个自定义风格的Button,然后在很多时候,我们只是想稍微修改下Button的外观,仍然像保留其阴影特性等功能,这时候我们就要"解剖"Button来了解其内部结构,VS2012自带的Expression Blend 5就具有这样的解剖功能。

生成了这样的代码:
<Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
看的出来,是由一个Border里面放了一个ContentPresenter构成的,然后是触发器定义的默认行为,相对比较简单,像ScrollBar等控件内部是很复杂的。关于ContentPresent,我们将在第二小节详细描述。
接下来,我们以Selector中的ListBox为例,来说明DataTemplate和ItemsPanelTemplate。
<!--ItemsPanelTemplate-->
<ItemsPanelTemplate x:Key="itemspanel">
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
<!--DataTemplate-->
<DataTemplate x:Key="datatemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}" Width="30"/>
<TextBlock Text="{Binding Name}" Width="60"/>
<Image Source="{Binding imgPath}" Width="30"/>
</StackPanel>
</DataTemplate>
cs代码:
List<Student> studentList = new List<Student>()
{
new Student(){ID=,Name="Rethinker",imgPath="/TemplateDemo;component/Images/1.png"},
new Student(){ID=,Name="Jello",imgPath="/TemplateDemo;component/Images/2.png"},
new Student(){ID=,Name="Taffy",imgPath="/TemplateDemo;component/Images/3.png"}
};
this.lbStudentList.ItemsSource = studentList;
注意:这里Image的Source采用的是Pack Uri,详细内容请查看WPF中的Pack Uri
效果如下:

2.ContentPresenter
在第一节,我们发现在解剖的Button内部有个叫ContentPresenter的东东,根据名字也许你已经猜到它是干嘛的了,它就是呈现ContentControl的内容的。这里,当我们将ContentPresenter换成TextBlock好像效果也没变化。
<TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
我们知道TextBlock的Text属性是String类型,这就限制了其显示的丰富性。有人会说,既然这样那换成ContentControl算了,它可以显示更丰富的东西,类似这样:
<ContentControl Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
看起来也没什么问题,我们知道Button本身就是一个ContentControl,它是一个很重量级的Control,它的Content其实也是通过ContentPresenter来表现的,看起来ContentPresenter是一个更轻量级的Control。另外,ContentPresenter还有一个比较特别的地方,当你未指定它的Content时,它会默认去取该模板的使用者的Content。
在继承自ItemsControl的控件内部也有个类似的ItemsPresenter,它是来负责Item的展示。

在ItemsPresenter内部会以ItemsPanelTemplate中的容器作为自己的容器,会以ItemTemplate中的布局作为ListBoxItem的布局。当然,在具体显示内容的地方,还是要用到ContentTemplate的。归根结底,我们可以将Presenter看作是一个占位符,设置了Button的Content,它就获取,否则默认。
3.TemplatePart机制
TemplatePart机制是某些WPF控件,如ProgressBar等,通过内建的逻辑来控制控件的可是行为的方式。我们先来解剖下ProgressBar一探究竟。

我们发现里面有几个很特别的东西,一个名为PART_Track的Rectangle,一个名为PART_Indicator的Grid。这并不是偶然,实际上在ComboBox和TextBox中也有这样类似PART_×××这样命名的元素。在这些类的定义中,我们也会发现一些端倪,例如ProgressBar类的定义:
[TemplatePart(Name = "PART_GlowRect", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_Indicator", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_Track", Type = typeof(FrameworkElement))]
public class ProgressBar : RangeBase
{ }
ProgressBar用了TemplatePart这个Attribute,那它到底如何有何作用呢?实际上,如果在ControlTemplate中找到了这样的元素,就会应用一些附加的行为。
例如,在ComboBox的空间模板中有个名为PART_Popup的Popup,当它关闭时,ComboBox的DropDownClosed事件会自动触发,如果ComboBox控件模板中有名为PART_EditableTextBox的TextBox,它就会将用户的选项作为它的显示项。在后面的自定义控件这一篇中,我们也将使用它。
4.如何找Template中的控件
在Template的基类FrameworkTemplate中有FindName方法,通过它我们可以找到模板中的控件。这个方法对于ControlTemplate和ItemsPanelTemplate很直接有效,但是,在ItemsControl的DataTemplate中,因为展示的数据是集合,所以相对复杂些。在前面我们已经剖析了ListBox内部,这对于找控件是最本质的。我们将前面的DataTemplate稍微修改下,如下:
<!--DataTemplate-->
<DataTemplate x:Key="datatemplate">
<StackPanel x:Name="sp" Orientation="Horizontal">
<TextBlock x:Name="tbID" Text="{Binding ID}" Width="30"/>
<TextBlock x:Name="tbName" Text="{Binding Name}" Width="60"/>
<Image x:Name="tbImgPath" Source="{Binding imgPath}" Width="30"/>
<TextBlock x:Name="tbNameLen" Text="{Binding Path=Name.Length}" />
</StackPanel>
</DataTemplate>
要查找由某个ListBoxItem的DataTemplate生成的TextBlock元素,需要获得ListBoxItem,在该ListBoxItem内查找ContentPresenter,然后对在该 ContentPresenter 上设置的 DataTemplate 调用 FindName,在由ListBoxItem查找ContentPresenter时,需要遍历VisualTree,这里给出遍历方法:
class CommonHelper
{
public static T ChildOfType<T>(DependencyObject Parent) where T : DependencyObject
{
for (int i = ; i < VisualTreeHelper.GetChildrenCount(Parent); i++)
{
DependencyObject obj = VisualTreeHelper.GetChild(Parent, i);
if (obj != null && obj is T)
{
return (T)obj;
}
else
{
T child = ChildOfType<T>(obj);
if (child != null)
return child;
}
}
return default(T);
}
}
在这里通过监听ListBox的SelectionChanged事件来展示效果,cs代码:
private void lbStudentList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//第一步:找到ListBoxItem
ListBoxItem item = this.lbStudentList.ItemContainerGenerator.ContainerFromIndex(this.lbStudentList.SelectedIndex) as ListBoxItem;
if (item == null) return;
//第二步:遍历找到ContentPresenter,这里需要写个辅助方法
ContentPresenter cp = CommonHelper.ChildOfType<ContentPresenter>(item);
if (cp == null) return;
//第三步:找到DataTemplate
DataTemplate dt = cp.ContentTemplate;
//第四步:通过DataTemplate的FindName方法
TextBlock tb = dt.FindName("tbName", cp) as TextBlock;
if (tb != null)
MessageBox.Show(tb.Text);
}
效果如下:

最后,推荐几篇比较好的文章:
1)Creating WPF Data Templates in Code: The Right Way
2)Customizing WPF Expander with ControlTemplate
WPF学习(10)模板的更多相关文章
- WPF学习10:基于MVVM Light 制作图形编辑工具(1)
图形编辑器的功能如下图所示: 除了MVVM Light 框架是一个新东西之外,本文所涉及内容之前的WPF学习0-9基本都有相关介绍. 本节中,将搭建编辑器的界面,搭建MVVM Light 框架的使用环 ...
- nodeJs学习-10 模板引擎 ejs语法案例
ejs语法案例 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <t ...
- WPF学习11:基于MVVM Light 制作图形编辑工具(2)
本文是WPF学习10:基于MVVM Light 制作图形编辑工具(1)的后续 这一次的目标是完成 两个任务. 画布 效果: 画布上,选择的方案是:直接以Image作为画布,使用RenderTarget ...
- WPF学习之深入浅出话模板
图形用户界面应用程序较之控制台界面应用程序最大的好处就是界面友好.数据显示直观.CUI程序中数据只能以文本的形式线性显示,GUI程序则允许数据以文本.列表.图形等多种形式立体显示. 用户体验在GUI程 ...
- WPF学习12:基于MVVM Light 制作图形编辑工具(3)
本文是WPF学习11:基于MVVM Light 制作图形编辑工具(2)的后续 这一次的目标是完成 两个任务. 本节完成后的效果: 本文分为三个部分: 1.对之前代码不合理的地方重新设计. 2.图形可选 ...
- 【WPF学习】第五十章 故事板
正如上一章介绍,WPF动画通过一组动画类(Animation类)表示.使用少数几个熟悉设置相关信息,如开始值.结束值以及持续时间.这显然使得它们非常适合于XAML.不是很清晰的时:如何为特定的事件和属 ...
- WPF学习概述
引言 在桌面开发领域,虽然在某些领域,基于electron的跨平台方案能够为我们带来某些便利,但是由于WPF技术能够更好的运用Direct3D带来的性能提升.以及海量Windows操作系统和硬件资源的 ...
- WPF学习开发客户端软件-任务助手(下 2015年2月4日代码更新)
时光如梭,距离第一次写的 WPF学习开发客户端软件-任务助手(已上传源码) 已有三个多月,期间我断断续续地对该项目做了优化.完善等等工作,现在重新向大家介绍一下,希望各位可以使用,本软件以实用性为主 ...
- WPF学习之路初识
WPF学习之路初识 WPF 介绍 .NET Framework 4 .NET Framework 3.5 .NET Framework 3.0 Windows Presentation Found ...
- ThinkPhp学习10
原文:ThinkPhp学习10 查询操作 Action模块 User下的search public function search(){ //判断username是否已经传入,且不为空 if(isse ...
随机推荐
- 《Android内核剖析》读书笔记 第13章 View工作原理【View重绘过程】
计算视图大小的过程(Measure) 视图大小,准确的来说应该是指视图的布局大小:我们在layout.xml中为每个UI控件设置的layout_width/layout_height两个属性被用来设置 ...
- 依赖注入(DI)
依赖注入(DI) IoC主要体现了这样一种设计思想:通过将一组通用流程的控制从应用转移到框架之中以实现对流程的复用,同时采用“好莱坞原则”是应用程序以被动的方式实现对流程的定制.我们可以采用若干设 ...
- Flipping Game(枚举)
Flipping Game time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- 超炫HTML5 SVG聊天框拖拽弹性摇摆动画特效
这是一款很有创意的HTML5 SVG聊天框拖拽弹性摇摆动画特效. 用户能够用鼠标点击或用手滑动聊天框上的指定区域,该区域会以很有弹性的弹簧效果拉开聊天用户列表.点击一个用户头像后.又以同样的弹性特效切 ...
- 建立qemu桥接的网络连接
转载请注明出处谢谢:http://www.openext.org/2014/07/qemu-kvm-bridge-00 安装桥接工具:sudo apt-get install bridge-u ...
- 很实用的FTP操作类
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; using ...
- vim使用(三):.viminfo和.vimrc
1. viminfo 在vim中操作的行为,vim会自己主动记录下来,保存在 ~/.viminfo 文件里. 这样为了方便下次处理, 如:vim打开文件时,光标会自己主动在上次离开的位置显示. 原来搜 ...
- CSS预处理器——Sass、LESS和Stylus实践
CSS(Cascading Style Sheet)被译为级联样式表,做为一名前端从业人员来说,这个专业名词并不陌生,在行业中通常称之为“风格样式表(Style Sheet)”,它主要是用来进行网页风 ...
- 小强的HTML5移动开发之路(50)——jquerymobile页面初始化过程
为了方便说明和更加直观的展示jquerymobile的页面初始化过程以及各个事件的触发过程,我绘制了一幅流程图: 图中用红色框圈起来的是界面中的事件,測试代码例如以下: <!DOCTYPE ht ...
- 基于Tkinter利用python实现颜色空间转换程序
主要基于colorsys实现,例子是从hls转换到rgb,假设要换颜色空间非常easy仅仅须要改动一个函数 用到了Scale和Canvas组件 代码例如以下: from Tkinter import ...