Can't call a method from another window in C#

2019-06-21 17:57发布

问题:

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.

回答1:

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;
    }


}

Second Window

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();


    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ((MainWindow)this.Owner).Test();
    }
}


回答2:

Why do you try this way.

public string Test()
{

   return  "works";
}

 MainWindow mw = new MainWindow();


 // Your second form label.
 lblsecondwindow.Text = mw.Test();


回答3:

You are creating another object of MainWindow as below:

MainWindow mw = new MainWindow();

instead of creating new MainWindow object use the existing one(i'm assuming that you had already created MainWindow object before).

Try This:

oldmaindwindow.Test();//here oldmainwindow is an old object of MainWindow

if you can show the fullcode it heps us.



标签: c# class methods