从动画完成事件中获取元素

本文关键字:获取 元素 事件 动画 | 更新日期: 2023-09-27 17:53:58

从我的代码后面,我想在一个特定的UIElement上开始一个动画,当动画结束时,我想在UIElement上做一些其他的处理。我有麻烦弄清楚如何将我收到的AnimationClock对象转换为动画完成事件的发送者到执行动画的UIElement对象。

下面是我用来构建和启动动画的代码:
DoubleAnimation FadeOutAnim = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(.5));
FadeOutAnim.Completed += new EventHandler(FadeOutAnim_Completed);
UIElement element = lstMessages.ItemContainerGenerator.ContainerFromItem(sender) as UIElement;
if(element != null)
   element.BeginAnimation(UIElement.OpacityProperty, FadeOutAnim);

这里是我的完成事件,我想再次访问UIElement

void FadeOutAnim_Completed(object sender, EventArgs e)
    {
        UIElement animation = sender; //This is an AnimationClock and I can't seem to figure out how to get my UIElement back.
    }

从动画完成事件中获取元素

如果处理程序是无用的(我找不到一个方法来获得动画元素),您可以引发另一个事件,它包含该信息:

private event EventHandler FadeAnimationCompleted;
private void OnFadeAnimationCompleted(object sender)
{
    var handler = FadeAnimationCompleted;
    if (handler != null)
        handler(sender, null);
}
FadeAnimationCompleted += new EventHandler(This_FadeAnimationCompleted);
FadeOutAnim.Completed += (s, _) => OnAnimationCompleted(element);
void This_FadeAnimationCompleted(object sender, EventArgs e)
{
    //Sender is the UIElement
}

更简单的方法是在委托中直接调用方法:

FadeOutAnim.Completed += (s, _) => FadeAnimationCompleted(element);
void FadeAnimationCompleted(UIElement element)
{
    //Meaningful code goes here.
}