我正在尝试从用户控件访问父窗口。
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();
这是完美的作品
制作一个主窗口的静态实例,您可以在用户控件中简单地调用它:
看这个例子:
窗口1.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_Window1 = this;
}
public static Window1 _Window1 = new Window1();
}
用户控件1.CS
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void AddControl()
{
Window1._Window1.MainGrid.Children.Add(usercontrol2)
}
}