Home > Software engineering >  How to pass click button event to trigger another function in WPF main window?
How to pass click button event to trigger another function in WPF main window?

Time:08-19

I am new to C#/WPF with very little expertise and finding difficulty with this task.

I have a button :

private void scan_click(object sender,RoutedEventArgs e) {}
      

I have the main window in WPF :

public MainWindow()
{
InitializeComponent();
devicewatcher.finddevices();
}

I want the execution of devicewatcher.finddevices() to take place after the button is clicked. I have tried using an incremental counter but it did not work Any help with this issue would be immensely helpful.

CodePudding user response:

If you want to execute your finddevices(); method, you should put that method in click event of your scan_click button.

So it will be:

private void scan_click(object sender,RoutedEventArgs e) 
{
  devicewatcher.finddevices();
}

Of course if you are in the same scope of your MainWindow class.

CodePudding user response:

When you added the event scan_click (I think you created it from xaml file), you also created a method.

A method is a code segment identified by a signature (name, in / out parameters, return type). In your case, this method is private void scan_click(object sender,RoutedEventArgs e) {}.

See that curly braces {} at the end of that method? They serves as markers for method's start and end points.

That means if you want to execute something in that method, you have to put your code between that braces, like so:

private void scan_click(object sender,RoutedEventArgs e) 
{ // this is the start point
    devicewatcher.finddevices();
} // this is the end point.

// By the way, in C# lines starting with // are comments.

Not to criticize your question, but if that's all you need, please consider doing a google search for such basical knowledge ;)

  • Related