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.

Answers


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.

Hope this helps!


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.


Need Your Help

How to increase the timeout period of web service in asp.net?

.net winforms web-services timeout

I've created one web service which is of asmx type. And I'm using my web service in the .net windows application.

Difference between NativeGuid and Guid in Active Directory

.net-3.5 active-directory

I need to update some AD querying code and want to use the new .NET 3.5 System.DirectoryServices.AccountManagement objects to query AD in a managed way as opposed to our current method of using LDA...