首页 > 解决方案 > 未应用 WPF 悬停边框效果

问题描述

当鼠标悬停在 WPF 中的控件上时,我正在尝试(但失败)更改单选按钮上圆圈边框的颜色。我的 WPFStyle如下:

<Style TargetType="RadioButton"
        x:Key="RadioButtonStyling"
        BasedOn="{StaticResource {x:Type RadioButton}}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style

然后我在单选按钮上调用它,如下所示:

<RadioButton Style="{StaticResource RadioButtonStyling}" ... />

就目前而言,圆形的轮廓没有应用任何样式,它仍然是默认的蓝色(开箱即用的 Windows 式蓝色)。见下图

鼠标光标悬停在单选按钮上,显示轮廓保持蓝色,而不是红色

标签: wpfxamluser-interface

解决方案


WPF 中的每个控件都有不同的状态,例如inactivemouse-overpresseddisabled。如果您想修改某些状态,样式上的简单设置器将不起作用,因为控件模板中已经定义了触发器,这些触发器将覆盖您的触发器。

因此,您需要创建自定义控件模板。您可以使用 Visual Studio 或 Blend 等工具来自动提取您可以编辑的默认控件模板。提取后,您将获得一种或多种样式以及如下所示的画笔列表。

<SolidColorBrush x:Key="RadioButton.Static.Background" Color="#FFFFFFFF"/>
<SolidColorBrush x:Key="RadioButton.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="RadioButton.Static.Glyph" Color="#FF212121"/>
<SolidColorBrush x:Key="RadioButton.MouseOver.Background" Color="#FFF3F9FF"/>
<SolidColorBrush x:Key="RadioButton.MouseOver.Border" Color="#FF5593FF"/>
<SolidColorBrush x:Key="RadioButton.MouseOver.Glyph" Color="#FF212121"/>
<!-- ...and so on. -->

<Style x:Key="OptionMarkFocusVisual">
   <!-- ...style used for displaying focus. -->
</Style>
<Style x:Key="RadioButtonStyle" TargetType="{x:Type RadioButton}">
   <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
   <Setter Property="Background" Value="{StaticResource RadioButton.Static.Background}"/>
   <Setter Property="BorderBrush" Value="{StaticResource RadioButton.Static.Border}"/>
   <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
   <Setter Property="BorderThickness" Value="1"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type RadioButton}">
            <!-- ...control template to display the radio button -->
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

在您的情况下,您只需覆盖鼠标悬停状态的边框画笔。

<SolidColorBrush x:Key="RadioButton.MouseOver.Border" Color="Red"/>

然后将更改后的样式应用于单选按钮。

<RadioButton Style="{DynamicResource RadioButtonStyle}"/>

推荐阅读