I’m trying to store the currently active user control in my wpf application that is currently in use, however I’m not sure on how to do so.
I currently load the user control into my wpf window grid (MainContent) like this:
MyAccount control = new MyAccount();
MainContent.Children.Add(control);
But I need to be able to remove the current control and add a new one in its place however I can’t work out how to store the currently in use control.
Edit: Just to clarify, I want to store the controls name in memory so I can later call MainContent.Children.Remove(oldcontrol).
Your question contains the answer already – you just need to store the name of the control in memory. Just put it in a variable name outside of the function / in an object which will still be available when you come to remove the control so that you can still reference that variable.
That said, you may not need a variable at all, if the name of the control will always be the same (as implied by the currently chosen answer, which shows there’s only one control of type MyAccount). You just need to tell the control what its name is:
Add the control with a name:
Remove by name:
This should be more efficient than the above code, and means if you have more than one control of a given type you only remove the one you’re interested in – not all controls of that type (or given the break statement, whichever control happens to be first of that type).
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.removebykey.aspx