在运行时将usercontrol设置为另一个窗口的内容

时间:2021-10-12 19:53:04

I have a window that have a user control. This user control has a button which maximize the user control to full screen.

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

For achieving this I have created a temporary window which I scale to current screen bounds and set it content to the user control.

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

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();
        }
      }
    }

How can I set the usercontrol as content of the newly created window, by detaching it from owner window and when temp window is closed, re-attach the same to parent window.

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

2 个解决方案

#1


0  

Use

mywindow.Content = new MyuserControl();

Make sure for a control can have only one parent at a time. Detach from first window first and then attach it to other.

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

#2


0  

Why is it so complicated?

为什么这么复杂?

You just need to switch current host form to the fullscreen mode.

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

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

#1


0  

Use

mywindow.Content = new MyuserControl();

Make sure for a control can have only one parent at a time. Detach from first window first and then attach it to other.

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

#2


0  

Why is it so complicated?

为什么这么复杂?

You just need to switch current host form to the fullscreen mode.

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

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