Search code examples
c#wpfwindow

Move user control from main window to child window then back again to main window?


I have a MainWindow, a userControl and a childWindow. The MainWindow has an expander who's content is set as an instance of the userControl using the following code in MainWindowXaml.cs:

public userControl 
userControl1 = new userControl();  
public MainWindow()  
{  
InitializeComponent();  
expander.Content = userControl1;  
}  

Then I put userControl1 in childWindow on a button click (the button is present in the expander's header):

private void b_click(...)  
{  
Window window = new Window();  
window.Content = userControl1;  
window.Closing += childWindow_closing;
window.Show();  
expander.Visibility = Visibility.Collapsed;  
}  

It works.

Now I try to put userControl1 back to the expander during the childWindow closing event:

private void childWindow_closing(...)  
{  
expander.Visibility = Visibility.Visible;  
expander.Content = userControl1;  
}  

But, this is not working. The childWindow closes and expander is shown. But userControl1 is not shown in expander. Any clue as to why?

Note: All the above mentioned code is in the MainWindowXaml.cs file.


Solution

  • As @WSC suggests setting expander.Content = null; fixes the issue.