您的位置:首页 > 其它

FindName in Silverlight --- Walk through the viual tree

2010-05-24 14:42 549 查看
How do you obtain a reference to an ancestor (within the visual tree) of a Silverlight FrameworkElement, given its name? The question seems pretty straight forward. FrameworkElement exposes a method, aptly named FindName, which appears to do just that. Easy solution, right? Well....maybe.

Using the FindName method works great, as long as the object you're looking for resides within the same XAML namescope as the FrameworkElement. How do you know if your target object is in the same XAML namescope as your FrameworkElement?

After my research, i found if the control is inside the usercontrols which you are referencing, these kind of controls will not be found by FindName method. While if the target object you are looking for is in the same level of the XAML, they can be found.

However, they are still part of the visual tree, so there should be some way to walk the tree down. FrameworkElement doesn't appear to expose any members to facilitate this type of action. Still, there must be a way to do it

I found a method somewhere for this solution, It will find the object regardless of the XAML namescope.

public static class VisualTreeWalker
{
public static FrameworkElement FindName(string name, DependencyObject reference)
{
return FindName<FrameworkElement>(name, reference);
}

public static T FindName<T>(string name, DependencyObject reference) where T : FrameworkElement
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if (reference == null)
{
throw new ArgumentNullException("reference");
}
return FindNameInternal<T>(name, reference);
}

private static T FindNameInternal<T>(string name, DependencyObject reference) where T : FrameworkElement
{
foreach (DependencyObject obj in GetChildren(reference))
{
T elem = obj as T;
if (elem != null && elem.Name == name)
{
return elem;
}
elem = FindNameInternal<T>(name, obj);
if (elem != null)
{
return elem;
}
}
return null;
}

private static IEnumerable<DependencyObject> GetChildren(DependencyObject reference)
{
int childCount = VisualTreeHelper.GetChildrenCount(reference);
for (int i = 0; i < childCount; i++)
{
yield return VisualTreeHelper.GetChild(reference, i);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐