WPF 控件模板
示例一:
下面以Button控件为例:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="WPF0309.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="mybtnTem" TargetType="{x:Type Button}">
<Border BorderThickness="2" BorderBrush="Green" CornerRadius="10">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="❤"></TextBlock>
<ContentPresenter></ContentPresenter>
</StackPanel>
</Border>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Height="50" Width="100" Content="OK" Template="{StaticResource mybtnTem}"/>
</Grid>
</Window>
效果:
示例二:
<Window x:Class="WPF0418A.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="btnTemplate" TargetType="{x:Type Button}">
<Border BorderThickness="2" BorderBrush="Green" CornerRadius="10" Background="SkyBlue" Name="border">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"></ContentPresenter>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true" >
<Setter TargetName="border" Property="Background" Value="Red"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Button Content="GOOD" Template="{StaticResource btnTemplate}"/>
</StackPanel>
</Grid>
</Window>
效果:(按钮背景为浅蓝色,当鼠标放进去时变成红色。)
示例三:添加一个按钮的控件模板
1.新建一个资源字典文件:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Mainform">
<ControlTemplate x:Key="btnTemplate" TargetType="{x:Type Button}">
<Border Name="border">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"></ContentPresenter>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true" >
<Setter TargetName="border" Property="Background" Value="#1d953f"></Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="false" >
<Setter TargetName="border" Property="Background" Value="Green"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ResourceDictionary>
2.在App.xaml中添加对其的引用:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DictionaryStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
3.使用方法:
<Button Content="计算" Width="150" Template="{StaticResource btnTemplate}" Foreground="White" FontWeight="Bold"></Button>
效果:鼠标进入和离开按钮,按钮背景色改变