Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Intro:
Ok, so i'm currently working in C# WPF, what i've got is a mainWindow and a number of different usercontrols, The mainWindow has got a grid of which it's children are having UserControls added and removed.

However i am wanting to be able to remove and add a different UserControl to this mainWindow grid from within the default (or first loaded) UserControl. e.g from a button click inside the UserControl, once clicked changes to a specific different UserControl and loads that in the mainWindow Grid.Children attribute.

I've tried:
Window parent = this.Parent;
Window parentWindow = Window.GetWindow(userControlReference);

public UserControl()<br />
{<br />
     InitializeComponent();<br />
     this.Loaded += new RoutedEventHandler(UserControl_Loaded);<br />
}<br />
<br />
public void UserControl_Loaded(object sender, RoutedEventArgs e)<br />
{<br />
      Window parentWindow = Window.GetWindow(this);<br />
      MessageBox.Show(parentWindow.ToString());<br />
}


The above i tried to see what it was returning and it returned the location reference of my mainWindow (ProjectTest.Loader.Views.MainWindow) however as it is only the location reference (atleast i think that's what it's called, correct me if i'm wrong) I'm unable to use any controls or properties from the actual window itself.

So what ways are there for me to access the Grid and or mainWindow from the UserControl child (Grid Child)

Thanks for any help :)
Posted

Have you tried this?
How to get parent control in wpf?[^]

seems to be the same issue, just doing something slightly different with the information.

Also check this out:
http://www.haidermrizvi.com/getting-parent-control-of-a-control-in-wpf-through-code-or-at-runtime/#.VWVMK09VhBc[^]
 
Share this answer
 
v2
In my Feeling it is the wrong way what you want to do.
A UserControl normally is an element, which is used by/from a Parent-Class (for example a window) - not an element which uses it's Parent.

If you want to Access the elements of the Parent you have to know them and you have to create a Reference to each of them via the Parent.Controls-Collection.
If you do this your UserControl is not longer universal - it has a direct dependancy to the Parent-Class - and only to that class (or a class which is build up in the same way).
 
Share this answer
 
Comments
Member 11650340 27-May-15 10:51am    
Yes, i was able to figure the solution to this because of this way of thinking.. and due to a stackoverflow post at : http://stackoverflow.com/questions/16236905/access-parent-window-from-user-control, i changed the solutions around a little and it suited what i was after just fine :) Thanks for your input

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900