You need to enable JavaScript to run this app. 如何解决WPF用户控件鼠标悬停背景Brush动画连续过渡问题
优惠活动
大模型
产品
解决方案
定价
更多

如何解决WPF用户控件鼠标悬停背景Brush动画连续过渡问题

WPF 控件鼠标悬停背景平滑过渡动画实现方案

初始实现与问题

最初要实现用户控件鼠标悬停时背景Brush连续切换的动画,初始代码如下:

private void MainControl_MouseEnter(object sender, MouseEventArgs e)
{            
    BeginColorAnimation(Background, BackgroundHover);
}

private void BeginColorAnimation(Brush from, Brush to)
{            
    BrushAnimation anim = new BrushAnimation()
    {
        From = from,
        To = to,
        Duration = AnimationDuration
    };
    
    BackgroundBorder.BeginAnimation(Border.BackgroundProperty, anim);                        
}        

private void MainControl_MouseLeave(object sender, MouseEventArgs e)
{            
    BeginColorAnimation(BackgroundHover, Background);
}

初始实现存在的问题:快速在控件上移动鼠标时,控件背景会直接在默认背景与悬停背景两个Brush之间瞬间切换,不符合预期的平滑连续过渡效果。如果动画执行到一半鼠标就离开控件,会出现两个Brush之间来回弹跳的突兀效果。

尝试修改与报错

尝试将动画起始值改为控件当前实际的背景值,修改后代码如下:

private void MainControl_MouseEnter(object sender, MouseEventArgs e)
{            
    BeginColorAnimation(BackgroundBorder.Background, BackgroundHover);
}

private void MainControl_MouseLeave(object sender, MouseEventArgs e)
{            
    BeginColorAnimation(BackgroundBorder.Background, Background);
}

但运行时抛出System.InvalidOperationException异常,提示"This freezable cannot be frozen"。

最终解决方案

改用SolidColorBrush替代Brush类型,搭配ColorAnimation类实现需求,最终代码如下:

public bool BackgroundFrozen = true;

private void MainControl_MouseEnter(object sender, MouseEventArgs e)
{            
    BeginColorAnimation((SolidColorBrush)BackgroundBorder.Background, BackgroundHover);
}

private void BeginColorAnimation(SolidColorBrush from, SolidColorBrush to)
{
    if(BackgroundFrozen)
    {
        BackgroundBorder.Background = BackgroundBorder.Background.CloneCurrentValue();
        BackgroundFrozen = false;
    }

    ColorAnimation anim = new ColorAnimation()
    {                
        From = from.Color,
        To = to.Color,
        Duration = AnimationDuration
    };
    
    BackgroundBorder.Background.BeginAnimation(SolidColorBrush.ColorProperty, anim);
}        

private void MainControl_MouseLeave(object sender, MouseEventArgs e)
{            
    BeginColorAnimation((SolidColorBrush)BackgroundBorder.Background, Background);
}

实现原理

Border的Background属性初始为冻结状态,首次执行动画时调用CloneCurrentValue()方法解除冻结即可。每次动画都从当前背景的实际颜色值开始过渡,即便动画中途被打断,也会从当前的中间状态开始执行新的动画,完全避免了突兀的弹跳效果,实现了连续平滑的背景切换。

内容的提问来源于stack exchange,提问作者JustSharingSomeCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 11:15:03