简体   繁体   中英

How to close window?

I have a UserControl userControl1 with button. When user click button i create new UserControl and show it:

private void Button_UserControl1_Click(object sender, RoutedEventArgs e)
{                                           
    Window window = new Window
    {
        Title = "Control2",
        Content = _control2

    };
    _control2= new UserControl2(ref window);
    window.ShowDialog();
}

at UserControl2 when i desides to close myself (control2 window) (another button click):

private void btOk_Click(object sender, RoutedEventArgs e)
{          
    _parent.Close();  //_parent is ref window
}

But i can not close it!

Can you tell me: how to close created window ( control2 ) by clicking to button on control2 ?

Thank you!

This should close the parent window:

private void btOk_Click(object sender, RoutedEventArgs e)
{          
    Window.GetWindow(this).Close();
}

This way you don't need to have reference to the parent. GetWindow will always return the window that is hosting the UserControl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM