在我们构建程序外观的时候,总会出于美观或者业务逻辑的需求,需要定制更加酷炫或者复杂的控件,样式,已经允许我们更改控件或者元素的外观了,但是有一个问题,如果我们需要更大范围的更改,比如一个按钮,可以通过样式修改背景,前景,圆角,甚至特殊几何形状,字体等属性,但是如果我们需求是只要保留按钮的使用逻辑,就是点击处理某些事情,但是需要内部更加复杂,里面拥有列表等,这个时候模板就应运而生了。
控件模板:每个控件都有一个内置的方法,用于确定如何渲染控件(作为一组更基础的元素)。该方法称为控件模板(control template),是用xaml标记块定义的。
下面这个例子,自己做了一个针对button的模板,简单的改了下外观
<Window x:Class="WpfApplication10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="mybutton" TargetType="Button">
<Border BorderBrush="Pink" BorderThickness="3" CornerRadius="3" Background="AliceBlue" TextBlock.Foreground="Red" TextBlock.TextAlignment="Center" >
<ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}">
</ContentPresenter>
</Border>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Button Margin="5" Template="{StaticResource mybutton}">我是一个按钮</Button>
</StackPanel>
</Grid>
</Window>
当然,我们也可以对模板使用触发器,比如下面这个例子,我们就实现了获得焦点,显示红色的框,失去焦点,红色框消失。
<Window x:Class="WpfApplication10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="mybutton" TargetType="Button">
<Border >
<Grid>
<Rectangle Name="rect" Visibility="Hidden" Stroke="Red" StrokeThickness="3"></Rectangle>
<ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}">
</ContentPresenter>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter TargetName="rect" Property="Visibility" Value="Visible"></Setter>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="false">
<Setter TargetName="rect" Property="Visibility" Value="Hidden"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Button Margin="5" Template="{StaticResource mybutton}">我是一个按钮</Button>
<Button Content="Button"/>
</StackPanel>
</Grid>
</Window>
既然可以放触发器,那么当然可以放事件触发器了,既然可以放事件触发器,就可以通过事件触发动画了,既然可以搞事件触发器,当然可以搞样式触发啦,反正是只要是xaml中有的东西,都可以放到模板中,因为模板本来就是xaml构建的。