从动画完成事件中获取UIElement

时间:2011-04-27 21:48:49

标签: c# wpf animation casting uielement

从我的代码隐藏中,我想在特定的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.

    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

如果处理程序没用(我找不到恢复动画元素的方法),你可以引发另一个包含该信息的事件:

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.
}