Search code examples
c#objecteventswindows-phone-8

EventHandler with a different type of sender


I'm trying to implement drag and drop for a specific object of a Type that I've created in c# for windows phone 8. I'm using Manipulation Events like this :

deck[r[i, j]].card.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(ImageManipulationCompleted);

private void ImageManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
    //something
}

How can I change object to the type that I want ?


Solution

  • keyboardP's solution will work just fine. But I personally prefer to store the information I need in the Tag property of the control, which has been designed for this very purpose.

    deck[r[i, j]].card.Tag = deck[r[i, j]];
    deck[r[i, j]].card.ManipulationCompleted += ImageManipulationCompleted;
    
    private void ImageManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
    {
        var deck = (Deck)((FrameworkElement)sender).Tag;
    }
    

    The good side of keyboardP's approach is that, since you receive directly the desired object as a parameter of your method, it's easier to read. The downside is that you have to declare a custom delegate for every event you need, and you lose the ability to assign event handlers directly from the XAML. My solution is a bit harder to read, but addresses this point.

    In the end, which solution is better really depends on your tastes and your needs.