2013-04-26 98 views
19

我想從用戶控件訪問父窗口。從用戶控件訪問父窗口

userControl1 uc1 = new userControl1(); 

mainGrid.Children.Add(uc1); 

通過此代碼我加載userControl1到主網格。

但是,當我點擊userControl1裏面的一個按鈕,然後我想加載另一個userControl2mainGrid這是在主窗口?

回答

40

你試過

Window yourParentWindow = Window.GetWindow(userControl1); 
+0

是的,我嘗試過,但之後如何加載到mainGrid userControl2? – 2013-04-26 12:54:35

+0

Window yourParentWindow = Window.GetWindow(userControl1);您的ParentWindow.mainGrid.children.add(新的userControl2); ; 這是正確的編碼? – 2013-04-26 12:55:37

+0

yourParentWindow.mainGrid.Children.Add(new userControl2()) – 2013-04-26 13:00:12

0

使主窗口的靜態實例,你可以簡單地把它在你的用戶控件:

見這個例子:

Window1.cs

public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
      _Window1 = this; 
     } 
     public static Window1 _Window1 = new Window1(); 

    } 

UserControl1.CS

public partial class UserControl1 : UserControl 
    { 
     public UserControl1() 
     { 
      InitializeComponent(); 

     } 
     private void AddControl() 
     { 
      Window1._Window1.MainGrid.Children.Add(usercontrol2) 
     } 
    } 
+0

如果一次打開多個有問題的窗口實例,此解決方案將不起作用。我在你的評論中看到,你指的是「主窗口」這個工作(我猜這隻會是其中之一)。但是,應該指出的是,這並不適用於所有窗口類型。 – curob 2018-03-02 20:53:47

1

感謝您的幫助。我得到了另一種解決方案

((this.Parent) as Window).Content = new userControl2(); 

這完全是工作

+2

注意:在這裏您假設您的控件的父項將始終是一個Window實例。 – Crono 2016-02-03 13:49:24

11

這得到根級窗口:

Window parentWindow = Application.Current.MainWindow 

或直接父窗口

Window parentWindow = Window.GetWindow(this); 
0

的唯一原因建議

Window yourParentWindow = Window.GetWindow(userControl1); 

你沒有工作是因爲你沒有將它轉換爲正確的類型:

var win = Window.GetWindow(this) as MyCustomWindowType; 

if (win != null) { 
    win.DoMyCustomWhatEver() 
} else { 
    ReportError("Tough luck, this control works only in descendants of MyCustomWindowType"); 
} 

除非有必須是你的窗口的類型和控制之間方式更多的結合,我認爲你的方法糟糕的設計。

我建議通過控制將作爲構造參數運行的網格,使其成爲一個屬性或在任何Window內動態搜索適當的(根?)網格。

相關問題