Lazy Lion
Lazy Lion

Reputation: 861

Access parent window from User Control

I am trying to access parent window from user control.

userControl1 uc1 = new userControl1();

mainGrid.Children.Add(uc1);

through this code I load userControl1 to main grid.

But when I click on a button inside userControl1 then I want to load another userControl2 into mainGrid which is in main window?

Upvotes: 43

Views: 60725

Answers (6)

Suneth Thotagamuwa
Suneth Thotagamuwa

Reputation: 81

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);
}

Upvotes: 4

Miloslav Raus
Miloslav Raus

Reputation: 767

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.

Upvotes: 4

seabass2020
seabass2020

Reputation: 1123

This gets the root level window:

Window parentWindow = Application.Current.MainWindow

or the immediate parent window

Window parentWindow = Window.GetWindow(this);

Upvotes: 29

Lazy Lion
Lazy Lion

Reputation: 861

Thanks for help me guys. i got another solution

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

this is perfectly works

Upvotes: 0

KF2
KF2

Reputation: 10171

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)
        }
    }

Upvotes: -1

Vlad Bezden
Vlad Bezden

Reputation: 89745

Have you tried

Window yourParentWindow = Window.GetWindow(userControl1);

Upvotes: 78

Related Questions