我有一個擁有用戶控件的窗口。此用戶控件具有一個按鈕,可將用戶控制最大化爲全屏。在運行時將usercontrol設置爲另一個窗口的內容
爲了達到這個目的,我創建了一個臨時窗口,我縮放到當前屏幕邊界並將其內容設置爲用戶控件。
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
史蒂夫這段代碼是在usercontrol裏面,爲什麼我使用ownerWindow = Window.GetWindow(this);來找到hostingwindow。而且我不能讓內容爲空,因爲父窗口可能包含可能會丟失的其他用戶控件。 – Mohit
那麼,在這種情況下,你可以將你的用戶控件加入到它是唯一的孩子的面板中。然後設置panel.content = null應該是無害的。出於好奇,我發現[這個線程](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/588456aa-110c-4ad2-baf3-d6b44d8157c0/)討論了一個類似的問題。希望它有幫助 – Steve