0
votes

Imagine next situation: I do have application window with several usercontrols inside. They was displayed side by side in past, but now I want to show one of them in popup window. Not in Popup control but new Window.

See example XAML:

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wpfApplication3="clr-namespace:WpfApplication3"
    Title="MainWindow"
    Height="350"
    Width="525">
<Grid>
    <wpfApplication3:UserControl1 Visibility="Hidden"
                                  x:Name="UserControl1"/>
    <Button Click="ButtonBase_OnClick"
            Width="100"
            Height="60">open window</Button>
</Grid>

In code behind I need to deattach usercontrol from current Window and assign to new one:

  private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var parent = VisualTreeHelper.GetParent(UserControl1);
        if (parent != null)
        {
            parent.RemoveChild(UserControl1);
        }

        var w = new Window
        {
            Content = UserControl1,
            Title = "sample",
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.CanResize

        };
        w.Show();
    }

And after calling w.Show() I always getting blank white window.

If in button click handler change

Content = UserControl1

to

Content = new UserControl1()

I will get right content as well. But I can't use this way because I want to keep my usercontrol state during pop-out and pop-in events. So how can I show in new window existing usercontrol without recreating it?

2

2 Answers

1
votes

I am not sure how you are calling RemoveChild on a DependencyObject as that method doesn't seem to exist. Note that VisualTreeHelper.GetParent returns a DependencyObject so, the code you posted should not compile unless you have an Extension method somewhere defining RemoveChild.

In your case what you want to do is cast your parent object to type Grid or Panel and then remove the UserControl from the Children property, then set your UserControl as the Content of your window.

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    Grid parent = VisualTreeHelper.GetParent(UserControl1) as Grid;
    if (parent != null)
    {
        parent.Children.Remove(UserControl1);
    }

    var w = new Window
    {
        Content = UserControl1,
        Title = "sample",
        SizeToContent = SizeToContent.WidthAndHeight,
        ResizeMode = ResizeMode.CanResize

    };
    w.Show();
}
0
votes

There was a similar question asked here that gives a very detailed answer.

The quick answer is that you will have to remove the control from the main window and then add it to the popup window.