简体   繁体   中英

How do we Close a custom UserControl as Dialog?

I designed a UserControl and planning to display this as popup window when click a button in MainWindow .

I followed this Link . For open usercontrol as dialog window.

private void btnInstApp_Click(object sender, RoutedEventArgs e)
    {
        Window objWindow = new Window
        {
            Title = "Title 12345",
            WindowStyle = WindowStyle.None,
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            AllowsTransparency=true,
            Width = 500,
            Height = 200,
            Content = new ucInstrumentApp()
        };

        objWindow.ShowDialog();
    }

I used None as WindowStyle . And designed a custom close button in UserControl for close the popup/dialog window. I tried the given below code. But it's not working.

 private void btnClose_Click(object sender, RoutedEventArgs e)
 {      
        //this.Close(); //:not working      
        Window objWindow = new Window
        {               
            Content = new ucInstrumentApp()
        };

        objWindow.Close();
 }

I am new to WPF/Windows forms. Can you guys guide me to solve this issue.

You need to get the parent Window from your current UserControl and then Close it.

One solution to achieve such a thing could be the following one :

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
         Window parentWindow = Window.GetWindow((DependencyObject)sender);
         if (parentWindow != null)
         {
             parentWindow.Close();
         }
    }

As you can see, it's based on the Window.GetWindow method, here's its description :

Returns a reference to the Window object that hosts the content tree within which the dependency object is located.

try

private void btnClose_Click(object sender, RoutedEventArgs e)
{     
    this.Close();
}

That should work :-)

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