模板(Template)是控件另一种样式 它和样式(style)不同的是它允许已有的控件进行组合新的一个控件样式
那么先看一下最简单Template代码
xaml代码
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="44,30,0,0" Name="button1" VerticalAlignment="Top" Width="75" > <Button.Template> <ControlTemplate> <Border BorderThickness="3" BorderBrush="#FF6969FF"> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF6F97FF" Offset="0" /> <GradientStop Color="#FF0021FF" Offset="0.574" /> <GradientStop Color="#FF6C7BFF" Offset="1" /> </LinearGradientBrush> </Border.Background> <TextBlock Text="按钮" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Lime"></TextBlock> </Border> </ControlTemplate> </Button.Template> </Button>
效果图
那么复杂一些
<ControlTemplate x:Key="tpe"> <Border BorderThickness="3" BorderBrush="#FF6969FF"> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF6F97FF" Offset="0" /> <GradientStop Color="#FF0021FF" Offset="0.574" /> <GradientStop Color="#FF6C7BFF" Offset="1" /> </LinearGradientBrush> </Border.Background> <ContentPresenter VerticalAlignment="{ TemplateBinding VerticalAlignment }" HorizontalAlignment="Center"></ContentPresenter> </Border> </ControlTemplate> <Button Content="Button" Template="{StaticResource tpe}" Height="23" HorizontalAlignment="Left" Margin="44,30,0,0" Name="button1" VerticalAlignment="Top" Width="75" >
效果图
ContentPresenter表示针对Button的content属性一个映射方式
那么紫色代码有个TemplateBinding 它表示指定一个相关属性映射 映射Button的 VerticalAlignment 的值 还可以margin映射padding 因为它们两个兼容
在style可以用Template
xaml代码
<Style x:Key="s1" TargetType="Button"> <Setter Property="Template" Value="{StaticResource tpe}"></Setter> </Style> <Button Content="Button" Style="{StaticResource s1}" Height="23" HorizontalAlignment="Left" Margin="44,30,0,0" Name="button1" VerticalAlignment="Top" Width="75" >
不过如果在style中设置某个属性的值 那么Template的TemplateBinding映射这个属性的值 不在控件上映射了
时间: 2024-12-27 07:48:09