Access parent window from User Control

前端 未结 6 1166
感动是毒
感动是毒 2020-12-30 19:55

I am trying to access parent window from user control.

userControl1 uc1 = new userControl1();

mainGrid.Children.Add(uc1);

through this co

6条回答
  •  臣服心动
    2020-12-30 20:41

    Modify the constructor of the UserControl to accept a parameter of MainWindow object. Then pass the MainWindow object to the UserControl when creating in the MainWindow.

    MainWindow

    public MainWindow(){
        InitializeComponent();
        userControl1 uc1 = new userControl1(this);
    }
    

    UserControl

    MainWindow mw;
    public userControl1(MainWindow recievedWindow){
        mw = recievedWindow;
    }
    

    Example Event in the UserControl

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        mw.mainGrid.Children.Add(this);
    }
    

提交回复
热议问题