WPF : ControlTemplate和DataTemplate的区别
ControlTemplate用于描述控件本身. 使用TemplateBinding来绑定控件自身的属性, 比如{TemplateBinding Background}
DataTemplate用于描述控件的Content. 使用Binding来绑定数据对象的属性, 比如{Binding PersonName}
一般来说, ControlTemplate内有一个ContentPresenter, 这个ContentPresenter的ContentTemplate就是DataTemplate类型
Control类型
- Template属性 (ControlTemplate类型)
- ContentPresenter
- ContentTemplate (DataTemplate类型)
ContentControl类型
- Template属性 (ControlTemplate类型) 继承自Control
- ContentTemplate (DataTemplate类型)
ItemsControl类型
- Template属性 (ControlTemplate类型) 继承自Control
- ItemsPanel属性 (ItemsPanelTemplate类型) 指定布局容器
- ItemTemplate属性 (DateTemplate类型) 每个Item的Template
<Style TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Ellipse Fill="{TemplateBinding Background}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
https://www.cnblogs.com/YangMark/p/3154375.html
一. 前言
什麼是DataTemplate? 什麼是ControlTemplate? 在stackoverflow有句簡短的解釋 "A DataTemplate, therefore, is used to provide visual structure for underlying data, while a ControlTemplate has nothing to do with underlying data and simply provides visual layout for the control itself."
意思是說,DataTemplate被使用在提供底層的數據;ControlTemplate則被使用在對控件本身可見布局的樣式。因此關於DataTelmplate與ControlTemplate的不同之處,我們應該從控件是如何使用著手。
二. Control, ContentControl, and ItemsControl
由下面三個邏輯樹,可知道ContentControl與ItemsControl均繼承自Control。而Control又繼承FrameworkElement,莫名奇妙的我們又多了一個問題-為什麼控件都要繼承FrameworkElement呢?
FrameworkElement具備以下幾點特性:
1.布局(Layout):定義了MaxHeight與MinHeight等屬性,故當我們呼叫控件時,控件本身即會在UI上佔位。
2.生命週期事件:定義Loaded/UnLoaded等事件,可通知後端控件何時被加載。
3.DataContext:在MVVM設計模式下,我們通常會使用DataContext綁定我們的ViewModel,DataContext屬性就是由FrameworkElement所提供。
故控件均具有以上特性,因此我們能直接呼叫控件,並知道何時應該被加載。
以下是WPF中常使用的控件之結構樹狀圖
三. DataTemplate and ControlTemplate
上一章介紹完一些控件的特性以及附屬關係,現在該思考的是我們如何使用這些控件呢??如:ListBox出現時,我們需要的是底層數據能展示在UI上(DataTemplate);Button有時或許我們會希望能修改事件觸發(IsPress or IsMouseOver)的結果(ControlTemplate)。
因此我們可以說兩者最大的不同在於DataTemplate服務於無形的數據, ControlTemplate則服務於有形的Control。而ControlTemplate還有一個特別重要的屬性-Triggers, 我們可藉由Triggers控制Control本身的屬性。
以下將以Button為例,分別在DataTemplate與ControlTemplate中加上同樣的樣式, 我們就可以知道兩者的不同了。
DataTemplate
<Button> <Button.ContentTemplate> <DataTemplate> <Grid> <Ellipse x:Name="ellipse"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="blue"/> <GradientStop Offset="1" Color="LightBlue"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <Ellipse> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="White"/> <GradientStop Offset="1" Color="Transparent"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> </Grid> </DataTemplate> </Button.ContentTemplate> </Button>ControlTemplate
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70002.html
- 上一篇:C#中byte[]和byte*
- 下一篇:按钮(图片、单选、复选)