You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI:如何获取UIElement.Transitions属性的过渡完成回调

如何监听UIElement.Transitions中过渡动画的完成事件

是的,你可以监听过渡动画的完成通知,但由于Transition类本身没有直接暴露Completed事件,需要通过以下两种常见方式实现:

方法1:将过渡动画封装到Storyboard中监听完成事件

这种方式更灵活,适合自定义过渡逻辑,直接通过Storyboard.Completed事件获取通知:

XAML代码

<Grid x:Name="RootGrid">
    <Button x:Name="TriggerBtn" Content="触发过渡" Click="TriggerBtn_Click"/>
    <Rectangle x:Name="AnimatedRect" Width="200" Height="200" Fill="Blue" Opacity="0"/>
</Grid>

C#代码

private void TriggerBtn_Click(object sender, RoutedEventArgs e)
{
    // 创建过渡动画
    DoubleAnimation opacityAnim = new DoubleAnimation
    {
        From = 0,
        To = 1,
        Duration = TimeSpan.FromSeconds(0.5)
    };

    // 绑定到目标元素的属性
    Storyboard.SetTarget(opacityAnim, AnimatedRect);
    Storyboard.SetTargetProperty(opacityAnim, "Opacity");

    // 创建Storyboard并添加动画
    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(opacityAnim);

    // 监听完成事件
    storyboard.Completed += Transition_Completed;

    // 启动动画
    storyboard.Begin();
}

private void Transition_Completed(object sender, object e)
{
    // 过渡完成后的逻辑
    Debug.WriteLine("过渡动画已完成!");
}

方法2:监听主题过渡(如PaneThemeTransition)内部的动画完成事件

对于PaneThemeTransition这类系统主题过渡,我们可以通过Composition API找到其内部的动画对象,再监听完成事件:

C#代码

private void SetupPaneTransition()
{
    PaneThemeTransition transition = new PaneThemeTransition();
    // 将过渡添加到元素的Transitions集合
    AnimatedRect.Transitions = new TransitionCollection { transition };

    // 触发过渡(比如改变元素的可见性)
    AnimatedRect.Visibility = Visibility.Visible;

    // 延迟获取内部动画(确保过渡已启动)
    Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
    {
        // 获取元素的CompositionVisual
        var visual = ElementCompositionPreview.GetElementVisual(AnimatedRect);
        // 遍历所有动画并监听完成事件
        foreach (var animation in visual.GetAllAnimations())
        {
            animation.Completed += (s, args) =>
            {
                Debug.WriteLine("PaneThemeTransition 已完成!");
            };
        }
    });
}

// 扩展方法:递归获取Visual的所有子动画
public static IEnumerable<CompositionAnimation> GetAllAnimations(this CompositionVisual visual)
{
    var animations = visual.StartAnimationGroups.SelectMany(g => g.Animations);
    foreach (var child in visual.Children)
    {
        animations = animations.Concat(child.GetAllAnimations());
    }
    return animations;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:40:59