Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function when button is clicked in a different window (WPF app)

Tags:

c#

wpf

I launch a window from a page of my wpf app and I would like to call a function when a button is pressed in the child window

Here is the page that calls the window :

namespace AppWpf10
{
    public partial class Prepare : System.Windows.Controls.Page
    {
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Choice win2 = new Choice();
            win2.Show();
        }

        public void DoStuff()
        {
            //CODE THAT DOES STUFF
        }
    }
}

The window launched :

namespace appWpf10
{
    public partial class Choice : Window
    {
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}

So I would like DoStuff()to be called upon button1 being pressed in the other window. How should I do it ? By calling DoStuff() in button1_Click from the child window ? Or by adding an event "button1 pressed in the other window" ?

Either way, anyone knows how to write it ? Thanks in advance !

like image 516
Loukoum Mira Avatar asked Mar 24 '26 08:03

Loukoum Mira


1 Answers

One solution is to give parent to child window in constructor and then it can call its parent methods:

private void button_Click(object sender, RoutedEventArgs e)
{
    Choice win2 = new Choice(this);
    win2.Show();
}


public partial class Choice : Window
{
    Prepare parent;

    public Choice(Prepare parent)
    {
        this.parent = parent;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        parent.DoStuff();
        this.Close();
    }
}
like image 58
Martin Heralecký Avatar answered Mar 26 '26 22:03

Martin Heralecký