1

I don't understand what event parameters do in C#. Let's say we have a button called CoffeeButton, and clicking on it takes you to another Page called Coffee using a Frame called myFrame. This is my code:

private void CoffeButton_Click(object sender, RoutedEventArgs e)
{
     MyFrame.Navigate(typeof(Coffee));
}

What does object sender and RoutedEventArgs e do in this case?

Examples would be great!

mason
  • 31,774
  • 10
  • 77
  • 121
  • Same thing any parameters do in any method, provide input and context to the called method. In your example above `sender` is a reference to the clicked button, `e` is context about the click event. – Igor Mar 31 '17 at 20:04
  • sometimes you need to know who sent the event or for example you want to know what happened that caused this event e.g. ObservableCollection has CollectionChanged that tells you what items were added to the collection and what were deleted – FCin Mar 31 '17 at 20:07
  • Okay, but where the method is called? –  Mar 31 '17 at 20:07
  • The event is called in response the clicking the button... – Chris Hinton Mar 31 '17 at 20:09

1 Answers1

8

Normally, "sender" will be a reference to whatever object fired the event. So if, for example, you have more than one Button that all wire into the same button_Click handler function, the sender object would be a reference to whichever actual Button object was clicked.

The EventArgs object that's normally passed in as the second parameter is used for different things depending on the context. Generally, it's used to pass you additional information related to the event that happened. For example, in this case, the RouteEventArgs object provides a RoutedEvent property that you can look at if you need to.

Joe Irby
  • 649
  • 6
  • 7