Cannot implicitly convert the type "System.EventHandler" to "System.Windows.RoutedEventHandler" in C #

In a Windows phone application, I want to add a button dynamically, as shown below:

Button btn = new Button(); btn.Content = tb_groupname.Text; btn.Width = 200; btn.Height = 200; btn.Click += new EventHandler(btn_Click);//Click event 

But when I add a click event on my button, I get below the error:

 Cannot implicitly convert type 'System.EventHandler' to 'System.Windows.RoutedEventHandler' 

The following is the button click event method:

 private void btn_Click(object sender, EventArgs e) { textbox1.text = "ABC"; // For Example } 

I do not understand why he received this error. Please offer me, waiting for an answer. Thanks.

+6
source share
3 answers

The signature of your event handler is incorrect.

It should be:

 private void btn_Click(object sender, RoutedEventArgs e) 

And the purpose of Click should be changed to:

 btn.Click += new RoutedEventHandler(btn_Click);//Click event 
+8
source

You need to use the RoutedEventHandler (found in the System.Windows assembly).

In your case, you can change btn.Click += new EventHandler(btn_Click); on btn.Click += new System.Windows.RoutedEventHandler(btn_Click); ; and then change the value of EventArgs ob btn_Click to RoutedEventArgs .

Be sure to add a link to the System.Windows assembly or it will not compile!

Looking at MSDN, I got the following:

The RoutedEventHandler divider is used for any routable event that does not report event information in the event data. There are many such disparate events; Outstanding examples include Click and Loaded.

The most notable difference between writing a handler for a routed event, as opposed to a common CLR runtime event, is that the event sender (the element in which the handler is attached and called) cannot necessarily be considered the source of the event. The source is reported as a property in the case of the data source). The difference between the sender and the source is the result of an event routed to different elements, during a traversal a routed event through the element tree.

Link to msdn .

+1
source

Click the Route Event button, as Patrick Hoffman mentioned.

You can even cut back if you don't want a new event by simply writing btn.Click + = btn_Click;

0
source

Source: https://habr.com/ru/post/969886/


All Articles