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

18,845

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();
    }
}
Share:
18,845
Michal_Drwal
Author by

Michal_Drwal

Updated on June 20, 2022

Comments

  • Michal_Drwal
    Michal_Drwal almost 2 years

    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.