How to close parent windows using WPF User Control

后端 未结 3 1227
失恋的感觉
失恋的感觉 2021-02-14 10:38

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 Use
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 11:07

    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();
    

提交回复
热议问题