Ben
Ben

Reputation: 247

How to call a method from one window to another without creating an Instance?

On my Window, I click a button which then displays a pop-up window in front of my current window.

private void btnStandards_Click(object sender, RoutedEventArgs e)
{
    StandardChooseScreen ChooseScreen = new StandardChooseScreen();
    ChooseScreen.Show();     
}

On the pop-up window, the user must tick a checkbox and press the 'Next' button.

private void btnStandardOption_Click(object sender, RoutedEventArgs e)
{
    if (chkNewStandard.IsChecked == true)
    {
        CreateNewStandard = true;
        StandardRedirect(CreateNewStandard, EditExistsingStandard, DeleteAStandard);
        this.Close();
    }

As you can see from the button click, I am calling StandardDirect which is a method from my previous Window, yet the method needs an instance and I do not want to create a new one, is there a way to get the instance of the already opened Window in the background?

Upvotes: 0

Views: 476

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65097

Pass it through the constructor of your popup:

public class YourPopupWindow : Form {
     private YourMainWindow _mainWindow;

    public YourPopupWindow(YourMainWindow mainWindow) {
        _mainWindow = mainWindow;
    }

    private void btnStandardOption_Click(object sender, RoutedEventArgs e) {
        if (chkNewStandard.IsChecked) {
            CreateNewStandard = true;
            _mainWindow.StandardRedirect(CreateNewStandard, EditExistsingStandard, DeleteAStandard);
            // ^^^^^^^ this
            this.Close();
        }
    }
}

Your other option is to use ShowDialog.. so that your popup is a true modal window.

if (yourPopupInstance.ShowDialog() == DialogResult.OK) {
    if (yourPopupInstance.chkNewStandard.IsChecked) {
        CreateNewStandard = true;
        StandardRedirect(CreateNewStandard, EditExistsingStandard, DeleteAStandard);
        // you're still in the main window here
        yourPopupInstance.Close();
    }
}

Upvotes: 4

Related Questions