2012-06-06 26 views
1

我有一個擁有用戶控件的窗口。此用戶控件具有一個按鈕,可將用戶控制最大化爲全屏。在運行時將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(); 
     } 
     } 
    } 

我如何設置用戶控件作爲新創建的窗口的內容,由所有者窗口分離,並在關閉臨時窗口,重新連接到相同的父窗口。

+0

從來沒有使用WPF,所以我不發表這個答案,但內容是讀/寫。你可以簡單地說:'this.Content = null;'在賦值給tempFullScreenWindow之前? – Steve

+0

史蒂夫這段代碼是在usercontrol裏面,爲什麼我使用ownerWindow = Window.GetWindow(this);來找到hostingwindow。而且我不能讓內容爲空,因爲父窗口可能包含可能會丟失的其他用戶控件。 – Mohit

+0

那麼,在這種情況下,你可以將你的用戶控件加入到它是唯一的孩子的面板中。然後設置panel.content = null應該是無害的。出於好奇,我發現[這個線程](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/588456aa-110c-4ad2-baf3-d6b44d8157c0/)討論了一個類似的問題。希望它有幫助 – Steve

回答

0

使用

mywindow.Content = new MyuserControl(); 

確保了控制可以在同一時間只能有一個父。先從第一個窗口分離,然後將其連接到其他窗口。

+0

dat什麼我想要找到如何從用戶控件的代碼中從OwnerWindow中分離usercontrol的實例 – Mohit

+0

創建一個新的用戶控件實例,並將datacontext複製到新實例,並將新控件顯示爲新的全屏窗口的子控件。 – Mohit

0

爲什麼它如此複雜?

您只需將當前主機窗體切換到全屏模式。

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

我在當前主機中有兩個面板,我只想最大化託管用戶控件的右側面板。我也只在用戶控件中有最大化按鈕。另外我想在其他許多對話框中重新使用此控件。 – Mohit

+0

因此,您不需要移動控件,只需在其他表單上創建另一個實例,並將所有必需的數據發送到該控件實例。 –

相關問題