Style和Template的研究
参考资料
分析
- Template是用来重定义控件的结构和外观。
- Style是用来定义具体的属性值。
而Template又可以作为Style的一个属性。大概如下:
定义Template->调用同一模板,定义不同样式
结论
- 可以像我分析的那样使用,定义一个按钮样式,然后不同的按钮使用不同的外观。
- 也可以用Style定义完整的控件,因为Style包含了Template
Style可以设置控件的所有属性的,包括Template,见示例里的btnStyleWithTemplate
示例

<Page.Resources>
// 定义按钮模板
<ControlTemplate x:Key="btnTemplate" TargetType="Button">
<Border CornerRadius="25,25,25,25" Height="50" Background="{TemplateBinding Background}" Width="100">
<TextBlock Text="{TemplateBinding Content}" Width="auto" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
// 在模板基础上定义样式1
<Style x:Key="btnStyle1" TargetType="Button">
<Setter Property="Template" Value="{StaticResource btnTemplate}"/>
<Setter Property="Background" Value="Pink"/>
<Setter Property="Foreground" Value="Green"/>
</Style>
// 在模板基础上定义样式2
<Style x:Key="btnStyle2" TargetType="Button">
<Setter Property="Template" Value="{StaticResource btnTemplate}"/>
<Setter Property="Background" Value="Green"/>
<Setter Property="Foreground" Value="Blue"/>
</Style>
// 定义样式的同时定义模板
<Style x:Key="btnStyleWithTemplate" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="RootGrid" Background="{TemplateBinding Background}" CornerRadius="25,25,25,25" Height="50">
<ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
调用方法:
<Button Content="普通的普通的" HorizontalAlignment="Center" Width="auto"/>
<Button Template="{StaticResource btnTemplate}" Content="模板定义1" HorizontalAlignment="Center" Grid.Row="1"/>
<Button Style="{StaticResource btnStyle1}" Content="样式定义1" HorizontalAlignment="Center" Grid.Row="2"/>
<Button Style="{StaticResource btnStyle2}" Content="样式定义2" HorizontalAlignment="Center" Grid.Row="3"/>
<Button Style="{StaticResource btnStyleWithTemplate}" Content="样式+模板定义" HorizontalAlignment="Center" Grid.Row="4"/>
浙公网安备 33010602011771号