【WPF】XAML实现按钮背景图片的点击切换

时间:2020-12-10 15:29:11

原因:要做一组搜索结果的排序按钮(类似一组RadioButton),效果像下图这样。想法是使用原生的按钮控件,将文字左对齐,整个按钮背景是一张图片,通过样式Trigger控制字体变色、背景图切换。
需求:RadioButton开关按钮,点击后切换自身按钮的背景图片。

【WPF】XAML实现按钮背景图片的点击切换

MyRadioButton.xaml

<ResourceDictionary  x:Class="HomeDecorationPSD.Presentation.Style.MyRadioButton"
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:HomeDecorationPSD.Presentation.Style"
mc:Ignorable="d"> <ResourceDictionary.MergedDictionaries>
<!-- 引入颜色字符串 -->
<ResourceDictionary Source="/Presentation/Resources/ColorResources.xaml" />
</ResourceDictionary.MergedDictionaries> <Style x:Key="myRadioButton" TargetType="{x:Type RadioButton}">
<Setter Property="BorderThickness" Value="0"></Setter>
<Setter Property="Width" Value="80"></Setter>
<Setter Property="Height" Value="30"></Setter>
<Setter Property="Foreground" Value="{StaticResource LightGreyColor}"/> <Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<Grid x:Name="grid" VerticalAlignment="Center">
<Border x:Name="border" BorderThickness="1" BorderBrush="{StaticResource LightGreyColor}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
HorizontalAlignment="Center" Background="#E9E9E9" Padding="5,0,0,0">
<ContentPresenter Content="{TemplateBinding Content}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</Grid> <!-- 触发器:设置字体的颜色 -->
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Foreground" Value="{StaticResource SoftRedColor}"/> <!-- 被引入的颜色字符串 -->
<Setter TargetName="border" Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/HomeDecorationPSD;component/Presentation/Resources/Images/down_arrow_selected.png" Stretch="Fill"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="false">
<Setter Property="Foreground" Value="{StaticResource LightGreyColor}"/>
<Setter TargetName="border" Property="Background"> <!-- 必须指明TargetName -->
<Setter.Value>
<ImageBrush ImageSource="/HomeDecorationPSD;component/Presentation/Resources/Images/down_arrow.png" Stretch="Fill"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers> </ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

坑点:

  • ControlTemplate必须使用一个Border包裹。
  • 在Trigger中给按钮设置文字颜色时,使用Foreground不需要指明TargetName,但是给背景设置图片时,必须要指明TargetName,否则无效果。(非常坑爹,运行无报错,能看到文字变色,不能看到背景图)