zoukankan      html  css  js  c++  java
  • [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);
  • 相关阅读:
    随机小错2_0527
    随计小错
    C++实现读写文件
    03-树2 List Leaves (25 分)
    获取毫秒级的时间戳
    new对象时,类名后加括号与不加括号的区别
    FoxMail 7.2的邮件存储目录修改
    C/C++ 开源算法库
    VS2015的安装
    脏内存导致BUG的问题
  • 原文地址:https://www.cnblogs.com/slmk/p/3037756.html
Copyright © 2011-2022 走看看