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);
  • 相关阅读:
    WPF:改变ListBoxItem和ListViewItem的颜色
    WPF样式——经典博客
    WPF中的Style(风格,样式)
    WPF中的动画
    WPF StoryBoard用法
    WPF 单个触发器、多个触发器、多条件触发器
    WPF编程学习 —— 样式
    WFP学习好微博
    Style、ControlTemplate 和 DataTemplate 触发器
    Arcgis 中国区技术支持 官网
  • 原文地址:https://www.cnblogs.com/slmk/p/3037756.html
Copyright © 2011-2022 走看看