Hey guys,
What is the most efficient way to find the root element (for example a UserControl) from a child UI Element in code (not XAML)? Is tree walking the only option, or is there something that doesn’t imply recursion?
Cheers,
Laurent
--
Laurent Bugnion [Microsoft MVP, MCP]
Blog: http://blog.galasoft.ch
Support children in Calcutta: http://www.calcutta-espoir.ch
|
My business card as |
b.ElementName =
"TopLevelItem"; BindingOperations.SetBinding(myChild, ElementFinder.ElementProperty, b);
var theElementIWant = ElementFinder.GetElement(myChild);
ElementFinder.SetElement(myChild, null);
{
public static UIElement GetElement(DependencyObject obj){
return (UIElement)obj.GetValue(ElementProperty);}
public static void SetElement(DependencyObject obj, UIElement value)
{
obj.SetValue(ElementProperty, value);
}
public static readonly DependencyProperty ElementProperty = DependencyProperty.RegisterAttached(
"Element", typeof(UIElement), typeof(ElementFinder), new UIPropertyMetadata(
default(UIElement))
)
);
}
> If you wanted to just get to the root window, there is an inherited property so you could use Window.GetWindow().
Could you please elaborate on this?
Corrado
From: wpf-di...@googlegroups.com
[mailto:wpf-di...@googlegroups.com] On Behalf Of Andrew
Sent: mercoledì 17 giugno 2009 15:11
To: wpf-di...@googlegroups.com
Subject: [WPF Disciples] Re: Most efficient way to find the root
element?
I guess it depends on what you consider to be the root element. For an element within the template of a Control, you would likely use TemplatedParent. For other elements you would walk the logical tree (and fallback to the visual tree when there is no logical parent). If you wanted to just get to the root window, there is an inherited property so you could use Window.GetWindow().
-Andrew
From: Laurent Bugnion [MVP] <lau...@galasoft.ch>
To: wpf-di...@googlegroups.com
Sent: Wednesday, June 17, 2009 4:32:58 AM
FYI, I asked Varsha about the finding root element. Varsha is the Dev Lead for all tree services. Her answer is below (we were not missing a silver bullet).
“Yes tree walk is the only way. However you do not need to use recursion you can simply walk the parent chain in a loop (i.e. iteratively).”