How to search parents?
I have construction:
Grid a = ((((usercontrol.Parent as DockPanel).Parent as ScrollViewer).Parent as Grid)
Is it possible to find a tree or a parent element?
example: Grid a = GetFirstParent(userc开发者_Python百科ontrol,"Grid") Grid - is Type element
Grid a = userControl.FindParent<Grid>();
public static T FindParent<T>(this DependencyObject startElement)
where T : DependencyObject
{
DependencyObject parent = GetParentObject(startElement);
if (parent == null)
return null;
T typedParent = parent as T;
if (typedParent != null)
{
return typedParent;
}
return FindParent<T>(parent);
}
Use the VisualTreeHelper class.
It has a method, GetParent, that returns the parent of a control (a DependencyObject really).
精彩评论