原因:要做一組搜索結果的排序按鈕(類似一組RadioButton),效果像下圖這樣。想法是使用原生的按鈕控件,將文字左對齊,整個按鈕背景是一張圖片,通過樣式Trigger控制字體變色、背景圖切換。
需求:RadioButton開關按鈕,點擊后切換自身按鈕的背景圖片。

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,否則無效果。(非常坑爹,運行無報錯,能看到文字變色,不能看到背景圖)
