代码改变世界

[Silverlight]按类型查找模板控件里的子控件

2013-04-23 14:26  slmk  阅读(526)  评论(0编辑  收藏  举报

Silverlight中的控件是基于Xaml模板的控件树形结构,这给控件制作提供了很大的灵活性,可以组合,嵌套等。同时也给控件的查找造成了不便,Silverlight提供了VisualTreeHelper类帮助我们遍历控件树。例如我们要按照控件类型查找控件,可以采用下面的递归算法:

 public class VisualTree
    {
        public static void FindControlByType<T>(DependencyObject container,List<T> ls) where T : DependencyObject
        {
            FindControlByType<T>(container, null, ls);
        }

        public static void FindControlByType<T>(DependencyObject container, string name,List<T> ls) where T : DependencyObject
        {
            //for each child object in the container
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(container); i++)
            {
                //is the object of the type we are looking for?
                if (VisualTreeHelper.GetChild(container, i) is T && 
            (VisualTreeHelper.GetChild(container, i).GetValue(FrameworkElement.NameProperty).Equals(name) || name == null)) { T foundControl = (T)VisualTreeHelper.GetChild(container, i); ls.Add(foundControl); } //if not, does it have children? else if (VisualTreeHelper.GetChildrenCount(VisualTreeHelper.GetChild(container, i)) > 0) { //recursively look at its children FindControlByType<T>(VisualTreeHelper.GetChild(container, i), name, ls); } } } } }

调用非常简单:

 List<HyperlinkButton> ls = new List<HyperlinkButton>();
 VisualTree.FindControlByType<HyperlinkButton>(this.LinksStackPanel, ls);