首先理清几个概念,Template、ControlTemplate、ContentTemplate、DataTemplate、ContentControl
这几个东西名字都差不多,意思感觉也接近,初次接触真的难以理解,那么现在开始区分了:
1.子类:
ContentControl是Control的子类,专门用于显示内容的,如常用的Label就是ContentControl的子类
2.属性:
Template 是Control类的一个属性;
ContentTemplate是ContentControl的一个属性;
3.类型:
Control的Template属性是ControlTemplate类型的;
ContentControl的ContentTemplate属性是DataTemplate类型的;
4.用途:
ControlTemplate,顾名思义,是控制控件外观和结构的,一般对于某个控件的类型,如一个Button长什么样子,Buttton里有一个列表,列表左侧显示图片等;
DataTemplate,则是控制一个控件它的数据要如何呈现的,一般对于的是某种数据的类型,(一般是用来修饰其Content属性的),所以要求为该类型的属性赋值,
如:
Label的Content属性赋值后,可以设置Label的ContentTemplate;
ItemsControl的ItemsSource属性赋值后,可以设置其的ItemTemplate;
HeaderItemsControl的Header属性赋值后,可以设置其的HeaderTemplate;
5.WPF模板类的继承关系
FrameworkTemplate
派生出:
ControlTemplate(决定控件外观)、ItemsPanelTemplate(决定集合的容器)、DataTemplate(决定数据的呈现方式)
而DateTemplate又派生出 HierarchicalDataTemplate(层次数据模板,一般用于TreeView和Menu)
6.当然这里主要讲ControlTemplate
ControlTemplate类的作用是重新定义控件的视觉效果和触发状态。控件在获取焦点或者被按下时,一般会显示出不同的状态,以便于用户区分。系统控件的视觉状态都是事先已经设定好的。这样做的好处是,可以复用已有的代码,大大节省了UI界面开发周期。有时候,用户需要为控件设定自己想要的视觉效果,比如:按钮控件的皮肤,指定为自定义的风格。这时,就需要借助ControlTemplate类。以下是一个简单的例子:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--最小化按钮样式-->
<Style TargetType="Button" x:Key="MinBtnStyle">
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="ToolTip" Value="最小化"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Image Name="btnImg" Source="/WpfApp1;component/Images/WinButton/Minimize.png" Width="20" Height="20"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" TargetName="btnImg" Value="/WpfApp1;component/Images/WinButton/Minimize_Hover.png"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Source" TargetName="btnImg" Value="/WpfApp1;component/Images/WinButton/Minimize_Press.png"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary> <Button Style="{StaticResource MinBtnStyle}" />1:Style有TargetType属性,值为生效的对象控件,x:Key是命名的资源名,Setter的属性名有很多,Cursor大家不陌生,是鼠标移动到上面显示的样子,Hand代表手型,ToolTip指的是鼠标移动到上面显示的提示,类似placeholder,Template是模型,controlTmplate是行为,里面的TargetType和Style的一样,controlTemplateTriggers是个触发器集合,里面有单独的trigger,Trigger的Property是行为,有IsMouseOver和IsPressed等,IsMouseOver顾名思义是鼠标移入移出时触发,IsPressed是鼠标点击时或者松开触发,value为true或者false,对应移入移出或者点击,松开,触发器里面的Setter是设置器,Property是设置的属性名,Source是Image的一个属性,意思是设置图片,TargetName指的是目标名控件名,与x:key相对,value是对应的设置的值。
2:路径,/WpfApp1;component/指的是项目名字为WpfApp1的根目录,component/就是根目录,前面的;隔开,代表项目所在的路径。
本文介绍了WPF中的ControlTemplate、ContentTemplate和DataTemplate的区别,强调ControlTemplate用于定制控件外观和结构,而DataTemplate则控制数据的呈现方式。通过实例展示了如何使用ControlTemplate改变控件的视觉效果和状态,包括定义样式、触发器等,以实现自定义控件的视觉风格。
2248

被折叠的 条评论
为什么被折叠?



