Close parent window from PopUp in WPF

0

How about, in my application I have a Cancel button, when you click on it, a Pop Up window appears that asks if you want to cancel or not, when you click on it, you must close the Pop Up window and the window in the one that was and send me to the Home, he does it, but he does not close the parent window of Pop Up, do you have any idea how I can do it? I'm using WPF and the MVVM pattern.

This is the button code:

private void btn_yes_Click(object sender, RoutedEventArgs e)
    {
        Proyecto.Desktop.View.HomeView newWin = new HomeView();
        Proyecto.Desktop.View.ParentWindow parent= new ParentWindow();

        parent.Close();
        newWin.Show();
        this.Close();                                                       
     }

Thanks, Regards!

    
asked by Pistche Lawliet 12.07.2017 в 17:34
source

2 answers

0

The problem is that you do this:

Proyecto.Desktop.View.ParentWindow parent= new ParentWindow();
parent.Close();

parent is a new instance of ParentWindow , not the one that is already active and that you want to close. You can try to find it and close it if you find it. It would be something like this:

var parent= Application.Current.Windows.OfType<ParentWindow>().FirstOfDefault();
if (parent!=null)
{ 
    parent.Close();
}
    
answered by 12.07.2017 / 17:58
source
0

Declare the "parent" window in a static class but do not initialize it, you can do the same with the Dialog

public static class GlobalDialogs
{
    static ParentWindow _parentWindow;
    public static ParentWindow ParentWindow
    {
        get { return GlobalDialogs._parentWindow; }
        set { GlobalDialogs._parentWindow = value; }
    }

    static PopUpDialogWindow _popupDialog;
    public static PopUpDialogWindow PopupDialog
    {
        get { return GlobalDialogs._popupDialog; }
        set { GlobalDialogs._popupDialog = value; }
    }

}   

In the 'parent' window you need to open the popup, do so

public void AbrirPopup()
{
    if (GlobalDialogs.PopupDialog == null)
    {
        GlobalDialogs.PopupDialog = new PopupDialog();
        GlobalDialogs.PopupDialog.Closed += (a, b) => GlobalDialogs.PopupDialog = null;
        GlobalDialogs.PopupDialog.Show();
    }
    else
    {
        GlobalDialogs.PopupDialog.Show();              
        //GlobalDialogs.Topmost = true;  // important
        //GlobalDialogs.Topmost = false; // important
        //GlobalDialogs.Focus();
    }
}   

Now when you need to close the parent window from the PopupDialog just close the instance created in the static class from the same popup

public void CerrarParent()
{
    if (GlobalDialogs.ParentWindow != null)
    {
        GlobalDialogs.ParentWindow.Close();
    }   
}   

Another option is to use an interface type class and put a closing method on it

    
answered by 15.07.2017 в 02:10