Franz
Franz

Reputation: 5

Adding event to button programmatically

I want to add an event to a programmatically generated button like this:

Button activityButton = new Button();
activityButton.Click += new EventHandler(onChangeActivityFilter);

I'm getting the following exception in the 2nd line:

Cannot implicit convert type System.EventHandler to System.Windows.RoutedEventhandler

The onChangeActivityFilter methode looks like this:

private void onChangeActivityFilter(object sender, EventArgs e)
{

}

I'd like to know what I'm doing wrong.

Upvotes: 0

Views: 76

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

You need to create a instance of RoutedEventHandler:

activityButton.Click += new RoutedEventhandler(onChangeActivityFilter);

And also change the method signature:

private void onChangeActivityFilter(object sender, RoutedEventArgs e)
{

}

RoutedEvents where introduced with WPF.

Upvotes: 5

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

You can also use lambda functions

activityButton.Click += (sender, e) => 
{
    MessageBox.Show("the button was clicked");
};

Upvotes: 1

Related Questions