C# 背景在鼠标左键中更改,但在鼠标左键中未更改
我刚刚进入WPF。我有两个事件处理程序:C# 背景在鼠标左键中更改,但在鼠标左键中未更改,c#,wpf,xaml,C#,Wpf,Xaml,我刚刚进入WPF。我有两个事件处理程序: private void Mouse_Enter(object sender, MouseEventArgs e) { ((Button)sender).Background = Brushes.Red; } private void Mouse_Leave(object sender, MouseEventArgs e) { ((Button)sender).Background = Brushes.Black; } 当鼠标进入按钮区
private void Mouse_Enter(object sender, MouseEventArgs e)
{
((Button)sender).Background = Brushes.Red;
}
private void Mouse_Leave(object sender, MouseEventArgs e)
{
((Button)sender).Background = Brushes.Black;
}
当鼠标进入按钮区域时,什么也不会发生。但是,当离开按钮区域时,按钮确实会变黑。我在Mouse\u Enter
中放置了一个断点,它肯定在执行该方法,只是没有改变背景颜色
如何修复它?谢谢 之所以会发生这种情况,是因为默认按钮模板中有一个“内置”触发器,导致按钮忽略您在鼠标输入事件中更改其背景的尝试,您需要编辑模板并首先禁用触发器,请遵循以下步骤: 在Visual Studio编辑器中,右键单击您的按钮,然后选择“编辑模板”,然后选择“编辑副本…”命名您想要的样式,并在XAML中查找名为“IsMouseOver”的触发器,然后删除下面的两行
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
--- Delete this line <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
--- Delete this line <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
---删除这一行
---删除这一行
当鼠标进入时,您的按钮是否会将颜色更改为默认的“按钮悬停”颜色?@Fleury26是的。如果它不需要在c代码中,也可以在XAML中,我建议看一下,重新设置按钮样式的方法远不止覆盖背景颜色。可以找到默认模板,非常感谢,但我真的很想使用代码隐藏。当然不是为了生产,只是为了学习。请您解释一下,如果不使用XAML触发器,我将如何修复它?再次感谢!