【发布时间】:2013-02-20 01:33:35
【问题描述】:
我有一个带有用户控件的窗口。此用户控件有一个按钮,可将用户控件最大化到全屏。
为了实现这一点,我创建了一个临时窗口,我将其缩放到当前屏幕边界并将其内容设置为用户控件。
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();
}
}
}
如何将用户控件设置为新创建窗口的内容,方法是将其从所有者窗口中分离出来,当临时窗口关闭时,将其重新附加到父窗口。
【问题讨论】:
-
从未使用过 WPF,所以我不发布这个答案,但内容是读/写的。您能否简单地说:
this.Content = null;在分配给 tempFullScreenWindow 之前? -
Steve 这段代码在用户控件本身内部,这就是为什么我使用 ownerWindow = Window.GetWindow(this); 来查找托管窗口的原因。而且我不能使内容为空,因为父窗口可能包含其他可能丢失的用户控件。
-
好吧,在这种情况下,您可以将您的用户控件设置为一个面板,其中它是唯一的孩子。然后设置 panel.content = null 应该是无害的。出于好奇,我发现this thread 正在讨论类似的问题。希望对你有帮助
标签: c# wpf user-controls fullscreen