C# 将usercontrol设置为另一个窗口的内容';s在运行时的内容

C# 将usercontrol设置为另一个窗口的内容';s在运行时的内容,c#,wpf,user-controls,fullscreen,C#,Wpf,User Controls,Fullscreen,我有一个具有用户控件的窗口。此用户控件有一个按钮,可将用户控件最大化为全屏 为了实现这一点,我创建了一个临时窗口,将其缩放到当前屏幕边界,并将其内容设置为用户控件 private void OnBtnMaximizeClick(object sender, RoutedEventArgs e) { if (this.btnMaximize.IsChecked == true) { if (tempfullScreenWindow == null)

我有一个具有用户控件的窗口。此用户控件有一个按钮,可将用户控件最大化为全屏

为了实现这一点,我创建了一个临时窗口,将其缩放到当前屏幕边界,并将其内容设置为用户控件

private void OnBtnMaximizeClick(object sender, RoutedEventArgs e)
    {
      if (this.btnMaximize.IsChecked == true)
      {
        if (tempfullScreenWindow == null)
        {
          tempfullScreenWindow = new Window();
          tempfullScreenWindow.WindowStyle = WindowStyle.None;
          tempfullScreenWindow.ResizeMode = ResizeMode.NoResize;
        }
        var ownerWindow = Window.GetWindow(this);

        Screen screen = this.GetContainingScreen(ownerWindow);

        tempfullScreenWindow.Left = screen.WorkingArea.Left;
        tempfullScreenWindow.Top = screen.WorkingArea.Top;
        tempfullScreenWindow.Width = screen.Bounds.Width;
        tempfullScreenWindow.Height = screen.Bounds.Height;

        // InvalidOperationException comes here (Specified element is already the logical child of another element. Disconnect it first.)
        tempfullScreenWindow.Content = this;  

        tempfullScreenWindow.Owner = ownerWindow;
        tempfullScreenWindow.ShowDialog();
      }
      else
      {
        if (tempfullScreenWindow != null)
        {
          tempfullScreenWindow.Close();
        }
      }
    }

如何将usercontrol设置为新创建窗口的内容,方法是将其与所有者窗口分离,并在临时窗口关闭时将其重新附加到父窗口。

为什么如此复杂

您只需要将当前主机窗体切换到全屏模式

public void GoToFullScreen()
{
  this.FormBorderStyle = FormBorderStyle.None;
  this.WindowSate = FormWindowState.Maximized;
}
使用


确保控件一次只能有一个父控件。首先从第一个窗口分离,然后将其附加到另一个窗口。

从未使用过WPF,所以我不会发布此答案,但内容是读/写的。你能简单地说:
this.Content=null在分配给tempFullScreenWindow之前?Steve此代码在usercontrol本身内部,这就是我使用ownerWindow=Window.GetWindow(this);,查找hostingwindow的原因;。我不能将内容设为null,因为父窗口可能包含其他可能丢失的用户控件。那么,在这种情况下,您可以将usercontrol设置为面板的父级,在该面板中它是唯一的子级。然后设置panel.content=null应该是无害的。出于好奇,我发现讨论一个类似的问题。希望它能帮助我在当前主机中有两个面板,我只想最大化承载用户控件的右侧面板。我也有最大化按钮,在用户控制只。我还想在很多其他对话框中重复使用这个控件。所以你不需要移动控件,只需在另一个窗体上创建另一个实例,并将所有必需的数据发送到该控件实例。dats我试图找到的是如何将usercontrol实例与OwnerWindow从用户控件的Code分离创建一个新的用户控件实例,并将datacontext复制到新实例,并将新控件显示为新完整控件的子控件屏幕窗口。
mywindow.Content = new MyuserControl();