【发布时间】:2021-05-24 11:58:32
【问题描述】:
我希望在光标悬停在按钮上时更改按钮的背景。
我设法以一种使用“IsMouseOver”触发器的样式来做到这一点,该触发器将按钮的背景设置为红色。
当点击事件发生时,我还希望按钮在两种颜色之间改变它的背景。
我已经设法在窗口的代码隐藏中做到这一点,它在蓝色和绿色之间切换。
问题
只要我不点击按钮,触发器就会按预期工作。
当我单击按钮时,背景会按预期更改为蓝色或绿色。
如果我随后将按钮悬停,则在光标悬停时背景不会设置为红色。
XAML 代码
<Window x:Class="Main.MainWindow">
<Window.Resources>
<Style x:Key="FooStyle" TargetType="Button">
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Background" Value="Blue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="Transparent">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button x:Name="btnFoo"
Content="Foo"
Width="100"
Click="Foo_Click"
Style="{StaticResource FooStyle}" />
</StackPanel>
</Window>
窗口代码隐藏
private void Foo_Click(object sender, RoutedEventArgs e)
{
btnFoo.Background = btnFoo.Background == Brushes.Blue ? Brushes.Lime : Brushes.Blue;
}
我怀疑触发器确实有效,但问题出在其他地方。
可能是什么问题?
如何解决?
【问题讨论】:
标签: c# wpf button triggers ismouseover