当光标悬停在按钮上时,我希望按钮的背景发生变化。
我设法以一种使用“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;
}
我怀疑触发器确实有效,但问题在于这里的其他东西。
可能是什么问题呢?
如何解决这个问题?