Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello experts. I'm still a newbie to wpf and working of transferring one of my projects from winforms to wpf. I want to add a window inside another window then close the hosted window using its controls and or events. The thing i want to achieve in wpf is achieved in windows forms using the following code.

C#
Form2 f2;
        private void Form1_Load(object sender, EventArgs e)
        {
            f2 = new Form2();
            f2 .TopLevel = false;
            f2 .AutoScroll = true;
            this.Controls.Add(f2 );
            f2 .Show();
        }

closing Form2 from a button in form2
        private void button1_Click(object sender, EventArgs e)
        {
           this.Close();
        }

closing Form2 from a button in form2
        private void button1_Click(object sender, EventArgs e)
        {
           this.Controls.Remove(f2);
        }


I have managed to add a Window to a wpf grid(or content of the grid rather) using the following code

C#
Window2 w2;
        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            w2= new Window2 ();
            object childContent = w2.Content;
            w2.Content = null;
            grid1.Children.Add(childContent as UIElement);
        }


However i cannot seem to find any better way of clossing Window2 from either button1 on window2 or button1 on window one just like i did in winforms as demonstrated by the winform code above.

I do not want to clear the grid so as to get rid of f2 in window1.

i have tried the following

closing Window2 from a button in Window2
C#
private void button1_Click(object sender, EventArgs e)
       {
          this.Close(); // not working
       }

closing Window1 from a button in Window1
C#
private void button1_Click(object sender, EventArgs e)
        {
           grid1.Children.Remove(w2); // not working
           w2.Dispose(); // not working
        }

How can i achieve this. I would like to know how to open a window inside a wpf panel (eg grid) so that it can be closable from any of the windows just as i did in winforms. I have searched the internet but could not find any helpful link. Thank you for reading. Any form of help is appreciated.
Posted
Updated 7-Jul-15 0:04am
v2
Comments
johannesnestler 7-Jul-15 6:46am    
You don't have a window in a window here. You have just a grid with a visual tree (it happens to be the content of your window). What mean's close for your grid, just hide or replace the Content with null or something else.. Or use PopUp or ChildWindows...
Difficult to go with Windows-Forms "thinking" into a WPF Project. Tip: Have a look at MVVM pattern and how to avoid code-behind...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900