WPF 自定义按钮外形
WPF的按钮提供了Template模板,可以通过修改Template模板中的内容对按钮的样式进行自定义,完整代码Github自取。
使用Style定义扁平化的按钮样式
定义一个ButtonStyleDictonary.xaml
资源字典文件,在Control Template中定义一个带Border的按钮,然后定义Trigger
作为改变样式的触发器
<Style x:Key="FlatButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="True">
<TextBlock Text="{TemplateBinding Content}"
Foreground="{TemplateBinding Foreground}"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#2f96b4"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
WPF中使用ResourceDictonary 资源字典
引入在资源字典文件中定义公共的Template,然后在xaml窗口、自定义控件或者整个App当中调用
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ButtonStyleDictonary.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
然后就可以在窗体的xaml中应用刚才定义的属性了
<Button Style="{StaticResource FlatButtonStyle}" Width="64" Height="28">
Hello
</Button>
使用Style和Polygon自定义Button的外形
<Style x:Key="ArrowButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Polygon x:Name="border" Fill="{TemplateBinding Background}"
Points="0,0 2,0 1,1" Stroke="Black" StrokeThickness="2"
SnapsToDevicePixels="True"
Stretch="Uniform"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Fill" Value="gray"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Fill" Value="red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
效果如下
参考资料
感谢扫码支持