Since I have started learning C#, I have seen a few ways to handle events. Say I have a XAML button like this:
<Button x:Name="button" Content="Click me!"/>
Given this button, I have can hook up a click event in several ways:
Modify the
Click
property of the button to point to a method in the code behind like:<Button x:Name="button" Content="Click me!" Click="button_Click"/>
And then add that
button_Click
method to the code:private void button_Click(object sender, RoutedEventArgs e) { button.Content = "Ow >_<"; }
Handle the event through a delegate in the code behind:
button.Click += delegate { button.Content = "Ow >_<"; };
Handle the event through a lambda expression in the code behind:
button.Click += (object sender, RoutedEventArgs e) => { button.Content = "Ow >_<"; };
Given these three methods, I have a couple of questions:
- What is the fundamental difference between these methods.
- Are there any cases in which one method should be used instead of another. I have seen type 1 used mainly in WPF and WinRT application, but the other two I have only really seen when using Xamarin.