一、自定义按钮模版xaml代码
首先为模版中的元素设置Name属性,方便后面触发器设置。
属性触发器当关注的属性符合预设值时,自动应用对应的属性设置。当属性变化后会自动恢复到设置前的状态。
<Window注意:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ButtonTemplate"
xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="ButtonTemplate.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<Border BorderBrush="Orange" BorderThickness="3" CornerRadius="2" Background="Red" TextBlock.Foreground="White" Name="Border">
<Grid>
<Rectangle Name="FocusCue" Visibility="Hidden" Stroke="Black" StrokeThickness="1" StrokeDashArray="1 2" SnapsToDevicePixels="True"></Rectangle>
<ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}"></ContentPresenter>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Border" Property="Background" Value="IndianRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="DarkKhaki" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="FocusCue" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="TextBlock.Foreground" Value="Gray" />
<Setter TargetName="Border" Property="Background" Value="MistyRose" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel Margin="10">
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}" Name="cmdOne">A Simple Button with a Custom Template</Button>
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}" Name="cmdTwo">Another Button with a Custom Template</Button>
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}" Name="cmdThree">A Third Button</Button>
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}" Name="cmdFour" IsEnabled="False">A Disabled Button</Button>
</StackPanel>
</Window>
①IsEnabled触发器要放在最后定义,这样可确保该规则优先于其它冲突的触发器设置。
②通过IsKeyboardFocused触发器实现虚线边框Rectangle的显示
二、效果演示