开发者

How to add event handler programmatically in WPF like one can do in Winform

开发者 https://www.devze.com 2023-02-03 13:22 出处:网络
What\'s the equivalent of this winform instruction: this.button1.Click += new System.EventHandler(this.button1_Click);

What's the equivalent of this winform instruction:

this.button1.Click += new System.EventHandler(this.button1_Click);

in WPF ?

U开发者_开发技巧pdate: also for a slider. And what namespace should I declare ?

My point is NOT to use XAML.


Something like this...

this.btnTest.Click+=new RoutedEventHandler(btnTest_Click);


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();
    }


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消