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


    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);
  • 相关阅读:
    迪杰斯特拉 优先队列 模板
    UVa 12186 树形dp
    树形dp总结
    codeforces 746C 模拟
    2017西安网络赛 F
    北京师范大学校赛C
    UVA 1584 字符串
    状压dp入门第一题 poj3254
    2017ICPC/广西邀请赛1005(水)HDU6186
    2017ICPC/广西邀请赛1001(水)HDU6181
  • 原文地址:https://www.cnblogs.com/slmk/p/3037756.html
Copyright © 2020-2023  润新知