Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

methods

c#

class

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.

like image 555
Michal_Drwal Avatar asked Nov 16 '13 04:11

Michal_Drwal


1 Answers

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();
    }
}
like image 62
Mark Hall Avatar answered Sep 22 '22 12:09

Mark Hall