Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we Close a custom UserControl as Dialog?

Tags:

c#

wpf

.net-4.0

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.

like image 427
Manikandan Sethuraju Avatar asked Feb 15 '23 18:02

Manikandan Sethuraju


2 Answers

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.

like image 173
AirL Avatar answered Feb 19 '23 21:02

AirL


try

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

That should work :-)

like image 38
Stefan Avatar answered Feb 19 '23 21:02

Stefan