在运行时将用户控件设置为另一个窗口的内容
本文关键字:窗口 另一个 设置 运行时 用户 控件 | 更新日期: 2023-09-27 18:36:21
我有一个具有用户控件的窗口。此用户控件有一个按钮,可将用户控件最大化为全屏。
为了实现这一点,我创建了一个临时窗口,我将其缩放到当前屏幕边界并将其内容设置为用户控件。
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();
}
}
}
如何将用户控件设置为新创建的窗口的内容,方法是将其与所有者窗口分离,并在临时窗口关闭时将其重新附加到父窗口。
使用
mywindow.Content = new MyuserControl();
确保控件一次只能有一个父控件。首先从第一个窗口分离,然后将其附加到另一个窗口。
为什么这么复杂?
您只需要将当前主机形式切换到全屏模式。
public void GoToFullScreen()
{
this.FormBorderStyle = FormBorderStyle.None;
this.WindowSate = FormWindowState.Maximized;
}