/// <summary>
/// Searchs an element in the visual tree matching with the given hash code.
/// </summary>
/// <param name="obj">A element in the visual tree as root element to search downwards the tree.</param>
/// <param name="hashCode">The hash code to search for.</param>
/// <returns>The element in the visual three matching the given hash code, otherwise null</returns>
/// <remarks>
/// This method is especially used in case where the visual tree is not part of the
/// main visual tree of the Silverlight application, as it happen with popup controls.
/// Optain the hash code from the output of WriteDownwards/WriteUpwards.
/// </remarks>
public static DependencyObject GetElementByHashCode(DependencyObject obj, int hashCode)
{
if (obj == null)
return null;
// check if hash code matches
if (obj.GetHashCode() == hashCode)
return obj;
// store child count local
int childCount = VisualTreeHelper.GetChildrenCount(obj);
// check if one of the child match to the hash code
for (int i = 0; i < childCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child.GetHashCode() == hashCode)
return child;
}
// go down the tree
for (int i = 0; i < childCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
DependencyObject returnObj = GetElementByHashCode(child, hashCode);
// if object was found, return
if (returnObj != null)
return returnObj;
}
// nothing found
return null;
}