C# wpf中 鼠标停在按钮上 实现呼吸灯效果 离开后恢复
时间: 2024-12-21 22:30:01 浏览: 32
在C# WPF中,要实现鼠标悬停在按钮上时产生呼吸灯效果,并在鼠标离开后恢复原状,可以通过使用Storyboard和ColorAnimation来实现。以下是一个简单的示例代码:
首先,你需要在XAML中定义一个Button,并为其添加MouseEnter和MouseLeave事件处理程序:
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Hover Me" Width="100" Height="50" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave"/>
</Grid>
</Window>
然后,在后台代码(C#)中,你可以定义两个Storyboard来分别处理鼠标进入和离开的事件:
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
var button = sender as Button;
if (button != null)
{
// 创建颜色动画
ColorAnimation colorAnimation = new ColorAnimation
{
From = Colors.Red,
To = Colors.Blue,
Duration = TimeSpan.FromSeconds(1),
AutoReverse = true,
RepeatBehavior = RepeatBehavior.Forever
};
// 应用动画到按钮的背景色
button.Background = new SolidColorBrush(Colors.Red);
button.BeginAnimation(Button.BackgroundProperty, colorAnimation);
}
}
private void Button_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
var button = sender as Button;
if (button != null)
{
// 停止所有动画并恢复原始背景色
button.Background = Brushes.Transparent;
button.BeginAnimation(Button.BackgroundProperty, null);
}
}
}
}
在这个例子中,当鼠标悬停在按钮上时,按钮的背景色会从红色渐变到蓝色,并且这个动画会无限重复。当鼠标离开按钮时,动画会停止,并且按钮的背景色会恢复到透明。
阅读全文
相关推荐

















