0

I'm trying to add an event handler to Click event

Button btn = new Button();
btn.Height = 40;
btn.Width = 120;    
btn.Click += new RoutedEventHandler(ShowRes);
mainPanel.Children.Add(btn);

It only works when method ShowRes() is static, but I need it to be non-static to change textBoxes in my wpf window by this method. When I'm trying to add non-static method it throws an exception An object reference is required for the non-static field, method, or property "MainWindow.ShowRes(object, RoutedEventArgs)"

private void ShowRes(object sender, RoutedEventArgs e)

How can I achieve it?

KindFrog
  • 358
  • 4
  • 17
  • Can you add the context of your `btn.Click += new RoutedEventHandler(ShowRes);` line as well as an explanation of *why* you need it to be non-static? – Klaycon Jun 23 '20 at 18:07
  • I need it to be non-static because it has to change textboxes in my wpf window – KindFrog Jun 23 '20 at 18:12
  • Makes sense. It seems like you've introduced static methods where they should not be in your code and it's making things difficult. At the very least, if you can edit in the method containing your `btn.Click += new RoutedEventHandler(ShowRes);` line, we can give appropriate guidance. Otherwise a general answer is the only one possible. – Klaycon Jun 23 '20 at 18:14
  • 1
    I don't believe there is *exception* like that... Are you absolutely sure you are getting *runtime exception* and not *compile time error*? (consider [edit] post to clarify) – Alexei Levenkov Jun 23 '20 at 18:20
  • Yes, you're right. `btn.Click += new RoutedEventHandler(ShowRes);` was written in a static method. – KindFrog Jun 23 '20 at 18:23

0 Answers0