我想从用户控件访问父窗口。从用户控件访问父窗口
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