Associating data with an event

I just solved the following problem - best explained by concrete example:

WPF Animation.Completed is an event. I need to register this event and when it fires, access custom data associated with the event:

void animate(Graph graph)

{

    PointAnimation anim = new PointAnimation();

    anim.Completed += new EventHandler(anim_Completed);

 

    // in anim_Completed, I want to call graph.Fix() - how?

}

 

void anim_Completed(object sender, EventArgs e)

{

    // how do I access 'graph' here?

}



Seems like a tough problem. Remembering 'graph' in eg. static variable is not an option, especially if we have more graphs animated at the same time.
Fortunately, C#'s lambdas come to the rescue:

void animate(Graph graph)

{

    PointAnimation anim = new PointAnimation();

    anim.Completed += new EventHandler((s, e) => { graph.Fix(); });

}



This works because anonymous methods bind to outer variables.

Posted by Martin Konicek on 2:55 PM

0 comments:

Post a Comment