Access parent window from User Control

前端 未结 6 1130
感动是毒
感动是毒 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:31

    Have you tried

    Window yourParentWindow = Window.GetWindow(userControl1);
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-30 20:41

    Make a static instance of main window ,you can simply call it in your user control:

    See this example:

    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)
            }
        }
    
    0 讨论(0)
  • 2020-12-30 20:49

    This gets the root level window:

    Window parentWindow = Application.Current.MainWindow
    

    or the immediate parent window

    Window parentWindow = Window.GetWindow(this);
    
    0 讨论(0)
  • 2020-12-30 20:54

    Thanks for help me guys. i got another solution

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

    this is perfectly works

    0 讨论(0)
  • 2020-12-30 20:55

    The only reason why the suggested

    Window yourParentWindow = Window.GetWindow(userControl1);
    

    didnt work for you is because you didn't cast it to the right type:

    var win = Window.GetWindow(this) as MyCustomWindowType;
    
    if (win != null) {
        win.DoMyCustomWhatEver()
    } else {
        ReportError("Tough luck, this control works only in descendants of MyCustomWindowType");
    }
    

    Unless there has to be way more coupling between your type of windows and your control, I consider your approach bad design .

    I'd suggest to pass the grid on which the control will operate as a constructor parameter, make it into a property or search for appropriate (root ?) grid inside any Window dynamically.

    0 讨论(0)
提交回复
热议问题