Home > Uncategorized > Walking the XAML VisualTree to find a parent of type <T>

Walking the XAML VisualTree to find a parent of type <T>

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:

image

BIG shout out goes to Jedi Master Twist for the lead on this :-)

About these ads
Categories: Uncategorized Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: