Search code examples
c#wpfxamlmouseeventsender

How to identify the sender of an event


I have a to-do software application in which I dynamically create each to-do task. I have a checkmark image on each task that when clicked, calls a MouseLeftButtonDown event. It works perfectly fine, but I need to identify which task I clicked on. Here's how I'm doing it so far:

private void CreateTask() {
    Image checkmarkImage = new Image();
    checkmarkImage.MouseLeftButtonDown += checkmarkPressed;
}
private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
    Console.WriteLine("Pressed");
}

Whenever the image is clicked on, the console writes "Pressed". Is there any way for me to identify which specific object called the function? It would be great if I could pass arguments to the CheckmarkPressed function like an integer; tasksAdded that could identify the specific task from any array. Anyone know how I can do this?

I tried things like sender.ToString() or e.Source but those just tell me that the sender was an image.


Solution

  • Assuming your are using the event handler CheckmarkPressed to be called only by the same type of objects, and that you are setting a unique identifier to recognize your objects, like @Ostas mentioned in his comment, you may use the property Tag for this purpose image.Tag = "checkbox" + tasksAdded (Quoted from your comment):

    private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
        var caller = (Image) sender;
        Console.WriteLine("Pressed by{0}",caller.Tag);
    }