Terry Thomas
Terry Thomas

Reputation: 41

Getting the UIElement from an animation completed event

From my codebehind I want to start an animation on a specific UIElement, when that animation ends I would like to do some other processing on that UIElement. I am having trouble figuring out how to convert the AnimationClock object that I receive as the sender of an Animation Completed event into the UIElement object that the animation was performed on.

Here is the code I use to build and start the animation:

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);

And here is my Completed event where I want access to the UIElement again.

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.

    }

Any help would be greatly appreciated.

Upvotes: 4

Views: 2571

Answers (1)

brunnerh
brunnerh

Reputation: 184752

If the handler is useless (i for one cannot find a way to get the animated element back), you could just raise another event which does contain that information:

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
}

Even easier would be to make a direct method-call in the delegate:

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

Upvotes: 7

Related Questions