To find a parent item of type T, you can use the following helper class:
public static class DependencyObjectHelper { public static DependencyObject FindParent(this DependencyObject obj, Predicate where) { var parent = VisualTreeHelper.GetParent(obj); if (parent == null || where(parent)) { return parent; } else { return parent.FindParent(where); } } public static T FindParentOfType(this DependencyObject obj) where T : DependencyObject { return (T)FindParent(obj, x => x is T); } }
This can then be utilised as follows:
Grid item = ((DependencyObject)childObject).FindParentOfType();
This was particularly useful when wanting to locate an invalid control from a ValidationSummary in silverlight, that was nested in an accordian panel:
BIG shout out goes to Jedi Master Twist for the lead on this 🙂
Leave a Reply