[英]Access parent window from User Control
我試圖從用戶控件訪問父窗口。
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
通過這段代碼我將userControl1
加載到主網格。
但是當我點擊userControl1
一個按鈕然后我想將另一個userControl2
加載到主窗口中的mainGrid
中?
你有沒有嘗試過
Window yourParentWindow = Window.GetWindow(userControl1);
這將獲得根級別窗口:
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
相應(根?)網格。
修改UserControl的構造函數以接受MainWindow對象的參數。 然后在MainWindow中創建時將MainWindow對象傳遞給UserControl。
主窗口
public MainWindow(){
InitializeComponent();
userControl1 uc1 = new userControl1(this);
}
用戶控件
MainWindow mw;
public userControl1(MainWindow recievedWindow){
mw = recievedWindow;
}
UserControl中的示例事件
private void Button_Click(object sender, RoutedEventArgs e)
{
mw.mainGrid.Children.Add(this);
}
謝謝你們的幫助。 我有另一種解決方案
((this.Parent) as Window).Content = new userControl2();
這是完美的作品
創建主窗口的靜態實例,您只需在用戶控件中調用它:
看這個例子:
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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.