Answered by:
Get Root UIElement?

Question
-
So we have the below method that gets the root most UIElement in the application (ie. the control that contains everything else)
public static UIElement GetApplicationRootUIElement() { if (Application.Current != null) return Application.Current.MainWindow as UIElement; else return null; }
This works great... that is if the application is a WPF app. But we have a requirment to use some WPF user controls in an Windows Forms app. So we attach the WPF control to a ElementHost control and almost have what we want. The problem is that Application.Current is null...Any other ways to get the root most WPF element without knowing about any of the other controls?
Thanks a lot!
Thursday, August 4, 2011 12:04 AM
Answers
-
VisualTreeHelper alows you to walk up or down a tree. VisualTreeHelper.GetParent should work for this. Just loop until GetPartent returns null.
Michael StacieThursday, August 4, 2011 3:11 PM
All replies
-
Not sure your question is clear.
1) Are you looking for the root element of entire application (i.e Winform and WPF) or just WPF part.
2) If the latter, (Say ElementHost control name is "elementHost") elementHost.Child will be the root WPF element.
Ajosh JoseThursday, August 4, 2011 2:23 AM -
Thanks for the reply Jose!
1) Looking for the root element of the WPF part.
2) So the only way would be to pass this elementHost.Child to the WPF control? There is no way for the WPF control to just find this out?
Thanks a lot!
Thursday, August 4, 2011 2:45 PM -
VisualTreeHelper alows you to walk up or down a tree. VisualTreeHelper.GetParent should work for this. Just loop until GetPartent returns null.
Michael StacieThursday, August 4, 2011 3:11 PM -
Hi Cood,
Ues this approach could get the element you want:
http://social.msdn.microsoft.com/forums/en-us/wpf/thread/B0A5BFCD-DB94-425D-9C56-07233441D055
Best regards,
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Friday, August 5, 2011 4:11 AM -
Thanks for all the ideas everyone... I ended up using Michael's approach and passing a child control and going down the tree. Thanks a lot!Friday, August 5, 2011 8:49 PM