Search code examples
c#wpfrouted-events

How to pass data into a RoutedEventHandler function


I'm working on a C# application that utilizes WPF and currently am looking to trigger an event when a TreeViewItem object receives focus. I've implemented this in a very basic manner with the following code:

Assigning the event:

TreeViewItem chr = new TreeViewItem();
chr.GotFocus += new RoutedEventHandler(testing);

The actual handler:

private void testing(object o, RoutedEventArgs e)
{
     MessageBox.Show("TESTING");             
}

This was simple enough, but I would also like to be able to use data from the object inside the eventhandler method. Something along the lines of this:

TreeViewItem chr = new TreeViewItem();
chr.GotFocus += new RoutedEventHandler(testing(chr));

I can't quite figure out how to do this and anything I do results in syntax errors. How is this normally done / is it even possible?

Any help is appreciated.


Solution

  • Use the sender parameter like the following:

    private void testing(object o, EventArgs e)
    {
         var treeViewItem = o as TreeViewItem;          
    }
    

    It happens that the sender object is actually the object that fired the event, TreeViewItem for your case