从用户控件访问父窗口

我试图从用户控件访问父窗口。

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动态搜索适当的(根?)网格。

谢谢你帮帮我们。 我有另一种解决方案

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

这是完美的作品

修改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); } 

创建主窗口的静态实例,您只需在用户控件中调用它:

看这个例子:

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) } }