Call function from another window

可紊 提交于 2019-12-11 18:06:20

问题


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.



来源:https://stackoverflow.com/questions/26085882/call-function-from-another-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!