从另一个窗口调用函数 [英] Call function from another window
问题描述
我从另一个窗口调用一个MainWindow函数时遇到问题。
I have a problem with call of one MainWindow function from another windows.
我有4个窗口:MainWindow,Window1,Window2和Window3。 MainWindow打开Window1,Window1打开window2,Window2打开Window3。我想从Window1和Window3调用MainWindow函数。我可以从Window1调用此函数,但是我不知道如何从Window3调用此函数。
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.
代码:从Window1调用MainWindow函数:
Code: call MainWindow function from Window1:
MainWindow:
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(); -要从MainWindow调用的函数
ruLanguage(); - functon to call from MainWindow
推荐答案
在WPF中,您可以通过 Application.MainWindow
属性
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();
}
您还可以在Windows上定义属性,因此可以像这样使用它们:
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();
}
然后传递 AppMainWindow $的值
And then pass the value of AppMainWindow
around.
另外,您可能需要重新考虑设计。了解MVVM模式,这是使用WPF的更好方法。
As a side note, you may want to reconsider your design. Learn about the MVVM pattern, it's the better way to use WPF.
这篇关于从另一个窗口调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!