我想從用戶控件訪問父窗口。從用戶控件訪問父窗口
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
通過此代碼我加載userControl1
到主網格。
但是,當我點擊userControl1
裏面的一個按鈕,然後我想加載另一個userControl2
到mainGrid
這是在主窗口?
我想從用戶控件訪問父窗口。從用戶控件訪問父窗口
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
通過此代碼我加載userControl1
到主網格。
但是,當我點擊userControl1
裏面的一個按鈕,然後我想加載另一個userControl2
到mainGrid
這是在主窗口?
你試過
Window yourParentWindow = Window.GetWindow(userControl1);
使主窗口的靜態實例,你可以簡單地把它在你的用戶控件:
見這個例子:
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)
}
}
如果一次打開多個有問題的窗口實例,此解決方案將不起作用。我在你的評論中看到,你指的是「主窗口」這個工作(我猜這隻會是其中之一)。但是,應該指出的是,這並不適用於所有窗口類型。 – curob 2018-03-02 20:53:47
感謝您的幫助。我得到了另一種解決方案
((this.Parent) as Window).Content = new userControl2();
這完全是工作
注意:在這裏您假設您的控件的父項將始終是一個Window實例。 – Crono 2016-02-03 13:49:24
這得到根級窗口:
Window parentWindow = Application.Current.MainWindow
或直接父窗口
Window parentWindow = Window.GetWindow(this);
的唯一原因建議
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
內動態搜索適當的(根?)網格。
是的,我嘗試過,但之後如何加載到mainGrid userControl2? – 2013-04-26 12:54:35
Window yourParentWindow = Window.GetWindow(userControl1);您的ParentWindow.mainGrid.children.add(新的userControl2); ; 這是正確的編碼? – 2013-04-26 12:55:37
yourParentWindow.mainGrid.Children.Add(new userControl2()) – 2013-04-26 13:00:12