How to close parent windows using WPF User Control
Asked Answered
L

3

13

Assume that I have two WPF windows: window_One and window_Two.

  • window_One has one button. Clicking this button opens window_Two.
  • window_Two contains a User Control.
    • This user control has one button that closes window_Two.

How can I achieve this scenario?

Labourer answered 30/9, 2015 at 12:7 Comment(0)
C
29

Inside the custom control that you've created. You can access the parent window from within the button event click.

Either by using the visual tree:

var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a => a is Window);
myWindow.Close();

or by simply:

var myWindow = Window.GetWindow(this);
myWindow.Close();

Of course, the other option would be to create a custom event that says "MyButtonClicked" and then have the window that hosts the UserControl to listen to this event and when the Event is fired, you close the current window.

Cheers!

Chalcocite answered 30/9, 2015 at 12:17 Comment(0)
A
3

We implemented this to close Window1 from Window2 getting opened, but it should work in any scenario to close any window from anywhere if you place these code parts in their appropriate areas:

Create a class that stores a Window object, and a function that will close it:

CloseWindow.cs

public static class CloseWindow
{
    public static Window WinObject;

    public static void CloseParent()
    {
        try
        {
            ((Window)WinObject).Close();
        }
        catch (Exception e)
        {
            string value = e.Message.ToString(); // do whatever with this
        }
    }
}

In the parent window (window you want to close - Window2, in this case?), in its onload event, set its Window object equal to CloseWindow.WinObject:

CloseWindow.WinObject = (Window)this;

Then, in the child's onload event (or, in the case of the OP, in Window2's User Control's button event), have it perform the CloseParent() function:

if (CloseWindow.WinObject != null)
    CloseWindow.CloseParent();
Alarcon answered 7/10, 2016 at 20:13 Comment(1)
This is an excellent solution for various scenarios as you wrote: it should work in any scenario to close any window from anywhere if you place these code parts in their appropriate areas. I can't than you enough for sharing your suggestion here. I tried many suggestions including the accepted answer of this post. But none of them work. I've a MS Office VSTO add-in where I have two WPF User Controls. Both are windows (Parent p) and its child c. I was able to close p from c using your code. Earlier I had spent all day struggling to get it work with no success. Many thanks to you and SO.Outbrave
A
0

You can try EventAggregator to implement this event driven logic across different ViewModel.

http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample

Amabil answered 1/10, 2015 at 7:24 Comment(1)
how is this closing the window?Amandie

© 2022 - 2024 — McMap. All rights reserved.