Wednesday, October 17, 2007

An extented VisualTreeHelper class

Usually if we want to get immediate parent of a Visual(Which considers the elements in Template also) we could use the VisualTreeHelper.GetParent method.This works easy for parent.
But think of getting the children of Visual..Its difficult to call VisualTreeHelper.GetChildren because this needs the index of child.
Here comes the role of this class which wraps these methods and makes its usage simple.

Code

public static class VisualTreeHelperEx
{
public static T FindVisualAncestorByType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T parent = default(T);
parent = FindVisualAncestorByType<T>(VisualTreeHelper.GetParent(dependencyObject));
return parent;
}
public static T FindVisualChildByType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T child = default(T);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
child = FindVisualChildByType<T>(VisualTreeHelper.GetChild(dependencyObject, i));
if (child != null) return child;
}
return null;
}
}

Usage


Window W = VisualTreeHelperEx.FindVisualAncestorByType <Window>(grd);
Rectangle r= VisualTreeHelperEx.FindVisualChildByType<Rectangle>(grd)

1 comment:

  1. Thanks for sharing. This came in really handly at work.

    ReplyDelete