ControlTemplate和DataTemplate
1.ControlTemplate主要是对控件的外观进行定义,控件就好比是一个房子,那么ControlTemplate就是房子的外观,外观怎样定义主要是依赖于ControlTemplate,例如:
<!--在代码内部定义ControlTemplate-->
<Button x:Name="_button">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Template">\
<Setter.Value>
<ControlTemplate TargetType="Button">
<!--定义控件的模板-->
<Border>
......
</Border>
<ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
<!--在Window.Resources中定义-->
<Window.Resources>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Template">\
<Setter.Value>
<ControlTemplate TargetType="Button">
<!--定义控件的模板-->
<Border>
......
</Border>
<ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.>
<!--引用Window.Resources中的Style-->
<Button Content="按钮" Style={StaticResource ButtonStyle}>
2.DataTemplate:如果说ControlTemplate是房子的外观,那么DataTemplate就是房子内部的装修,通俗的说就是房子内部的东西(数据)的外观,其使用举例如下:
<!--在控件内部使用-->
<ItemsControl x:Name="Itmes">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!--定义房子里家具的排列方式-->
<StacPanel Orientation="Vertical">
<ItemsPanelTemplate>
<ItemsControl.ItemsPanel>
<!--定义房子的外观-->
<ItemsControl.Style>
<Style>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border>
......
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Style>
<!--定义房子的内装修-->
<ItemsControl.ItemsTemplate>
<DataTempalte>
<Border>
......
</Border>
</DataTemplate>
</ItemsControl.ItemsTemplate>
<!--定义房子的内墙-->
<ItemsControl.ItemsContainerStyle>
<Style TargetType="Items">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border>
......
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemsContainerStyle>
</ItemsControl>