Can't change border color when mouse hover button
当鼠标悬停在按钮上时,我正在尝试更改默认边框颜色,但我无法让它工作。我认为这会很好,但显然它没有:
1 2 3 4 5 | <Button> <Button.Resources> <Color x:Key="ControlMouseOverColor">somecolor</Color> </Button.Resources> </Button> |
有没有办法做到这一点?
这是您需要做一些稍微复杂的事情才能在 WPF 中完成一些简单的事情的情况之一 :)。您实际上需要覆盖 Button 控件的 ControlTemplate,因为鼠标悬停在按钮上时的边框颜色由默认的 ControlTemplate 下面是一个带有默认 CotrolTemplate 的按钮,减去 IsMouseOver 设置器设置为红色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <Button> <Button.Template> <ControlTemplate TargetType="{x:Type ButtonBase}"> <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="Button.IsDefaulted" Value="True"> <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" TargetName="border" Value="#FFBEE6FD"/> <Setter Property="BorderBrush" TargetName="border" Value="Red"/> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" TargetName="border" Value="#FFC4E5F6"/> <Setter Property="BorderBrush" TargetName="border" Value="#FF2C628B"/> </Trigger> <Trigger Property="ToggleButton.IsChecked" Value="True"> <Setter Property="Background" TargetName="border" Value="#FFBCDDEE"/> <Setter Property="BorderBrush" TargetName="border" Value="#FF245A83"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Background" TargetName="border" Value="#FFF4F4F4"/> <Setter Property="BorderBrush" TargetName="border" Value="#FFADB2B5"/> <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="#FF838383"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> Click </Button> |
在 WPF 中正常的解决方案是属性触发器:
1 2 3 4 5 6 7 8 9 10 11 12 | <Button> <Button.Style> <Style TargetType="{x:Type Button}"> <Setter Property="BorderBrush" Value="Black"></Setter> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="BorderBrush" Value="Red"></Setter> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> |
属性触发器旨在在条件变为真时做出反应,但在条件变为假时恢复其先前的状态。所以在这里我们说:当 IsMouseOver 属性变为 true 时,将定义的按钮的边框画笔设置为红色。当条件变为假时,它会变回黑色(我不确定边框画笔的默认颜色是什么,所以你可以删除第 4 行)