'How to add event handler programmatically in WPF like one can do in Winform
What's the equivalent of this winform instruction:
this.button1.Click += new System.EventHandler(this.button1_Click);
in WPF ?
Update: also for a slider. And what namespace should I declare ?
My point is NOT to use XAML.
Solution 1:[1]
Try this:
button1.AddHandler(Button.ClickEvent, new RoutedEventHandler(button1_Click));
then you have to create a function like this
void button1_Click(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
Solution 2:[2]
If you're adding the new event from the XAML side, the IDE does most of the work for you.
For instance, if you type
<Button Name="button1" Click=
then the IDE will pop up with a drop-down of all your currently created events.
You can select one of your previously-created events, or create a new one by selecting "New Event Handler"
If you select "New Event Handler", then VS automatically adds the skeleton for you in the form.xaml.cs C# code-behind. You just add whatever you'd like the click event to do inside the already-made skeleton.
Solution 3:[3]
WPF isn't a new language, i.e., it's exactly the same concept. The only thing that may change is the delegate type. So yeah, you would do it the same way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Liam McInroy |
| Solution 2 | halfer |
| Solution 3 | Ed S. |
