35

我正在尝试从用户控件访问父窗口。

userControl1 uc1 = new userControl1();

mainGrid.Children.Add(uc1);

通过这段代码我加载userControl1到主网格。

但是当我点击里面的一个按钮时,userControl1我想加载另一个userControl2mainGrid主窗口中的按钮?

4

6 回答 6

67

你有没有尝试过

Window yourParentWindow = Window.GetWindow(userControl1);
于 2013-04-26T12:53:22.723 回答
25

这将获得根级窗口:

Window parentWindow = Application.Current.MainWindow

或直接父窗口

Window parentWindow = Window.GetWindow(this);
于 2014-12-04T21:49:25.323 回答
4

建议的唯一原因

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

于 2015-09-29T09:26:27.820 回答
4

修改 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);
}
于 2018-09-05T16:18:19.170 回答
0

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

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

这是完美的作品

于 2013-04-26T14:49:20.417 回答
-1

制作一个主窗口的静态实例,您可以在用户控件中简单地调用它:

看这个例子:

窗口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)
        }
    }
于 2013-04-26T13:38:14.383 回答