Question

I'm working on a simple IM program as a personal project, and I've hit a bit of a snag. It's really more of a cosmetic thing, but I'm having some trouble with it. I've got a sidebar that lists all of a user's contents in the main window, and I'd like to set it up so that when a user clicks on a contact name, a tab opens in the chat area of the main window with a chat session opened with that contact. The really important part of this is for me to be able to get the UIElement, in this case a Label, that kicked off the MouseDoubleClick event. Once I can access this, I can access the information that I need to make the connection. Unfortunately, I'm a bit rusty with mouse events, and can't figure out how to get back to the Label once the event has been fired. My source code for programmatically creating the label is as follows:

foreach (ContactInfo contact in ContactList)
{
    Label currentContact = new Label();
    currentContact.Content = contact.ContactName.ToString() + " (" + contact.MachineName.ToString() + ")";
    currentContact.MouseDoubleClick += new MouseButtonEventHandler(ContactDoubleClickHandler);
    StckPnl_Contacts.Children.Add(currentContact);
}

And the (currently empty) handler is this:

public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
{

}

Am I going about this the wrong way? Any help would be appreciated.

Was it helpful?

Solution

You can inspect the sender (first casting it to the type) to get the element that triggered the event:

Label targetLabel = sender as Label;
if (targetLabel != null)
{
    // Do something. I recommend not doing a direct cast in case someone in the future hooks another control type to the event handler.
}

OTHER TIPS

You can use either of following to access the sender details

public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
    {
       var uiElement = (UIElement) sender; // cast it to UIElement
    }


public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
    {
       var dp = (DependencyObject) sender; // cast it to dependency object.
    }

Actually, the sender is your Label, you just have to transform it using:

Label contact = sender as Label;

Be sure to check if contact is null though, before performing any further operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top