I am trying to access parent window from user control.
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
through this co
Have you tried
Window yourParentWindow = Window.GetWindow(userControl1);
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);
}
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)
}
}
This gets the root level window:
Window parentWindow = Application.Current.MainWindow
or the immediate parent window
Window parentWindow = Window.GetWindow(this);
Thanks for help me guys. i got another solution
((this.Parent) as Window).Content = new userControl2();
this is perfectly works
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.