无法从C#WPF中的另一个窗口调用方法 [英] Can't call a method from another window in C# WPF
本文介绍了无法从C#WPF中的另一个窗口调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,假设我有两个窗口。在第一个我有一个方法
Ok, let's say I have two windows. In the first one I have a method
public void Test()
{
Label.Content += " works";
}
在第二个我调用这个方法:
And in the second one I call this method:
MainWindow mw = new MainWindow();
mw.Test();
但没有任何反应。我做错了什么?谢谢。
But nothing happens. What am I doing wrong? Thanks.
推荐答案
您可以将所有者分配到在MainWindow中创建的窗口。
You can assign the Owner to the window that was created in your MainWindow.
window.Owner = this; //This is added to the code that use to create your Window
然后你应该能够访问这样的东西。
Then you should be able to access it something like this.
((MainWindow)this.Owner).Test();
MainWindow
public partial class MainWindow : Window
{
Window1 window = new Window1();
public MainWindow()
{
InitializeComponent();
window.Show();
}
public void Test()
{
label1.Content += " works";
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
window.Owner = this;
}
}
第二个窗口
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((MainWindow)this.Owner).Test();
}
}
这篇关于无法从C#WPF中的另一个窗口调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文