Call function from another window

2019-09-01 07:19发布

问题:

I have a problem with call of one MainWindow function from another windows.

I have 4 windows: MainWindow, Window1, Window2 and Window3. MainWindow open Window1, Window1 open window2 and Window2 open Window3. I want to call MainWindow function from Window1 and Window3. I can call this function from Window1 but i don't know how to do this from Window3.

Code: call MainWindow function from Window1:

MainWindow:

private void button2_Click(object sender, RoutedEventArgs e)
{
     Window1 w1 = new Window1();
     w1.Owner = this;
     w1.ShowDialog();
}

Window1:

public void button_cancel_Click(object sender, RoutedEventArgs e)
{         
    var myObject = this.Owner as MainWindow;
    myObject.ruLanguage();
}

ruLanguage(); - functon to call from MainWindow

回答1:

In WPF, you can access the main window through the Application.MainWindow property.

public void button_cancel_Click(object sender, RoutedEventArgs e)
{         
    var myObject = Application.MainWindow as MainWindow;
    myObject.ruLanguage();
}

You could also define properties on your windows, so you could use them like that:

public MainWindow AppMainWindow { get; set; }

private void button2_Click(object sender, RoutedEventArgs e)
{
     Window1 w1 = new Window1();
     w1.Owner = this;
     w1.AppMainWindow = this;
     w1.ShowDialog();
}

And then pass the value of AppMainWindow around.

As a side note, you may want to reconsider your design. Learn about the MVVM pattern, it's the better way to use WPF.