WPF 查找ListBox等DataTemplate下的子控件

2021-05-04 06:26

阅读:700

标签:children   item   top   ems   break   where   help   temp   好的   

做项目时找到的方法,引用自http://bbs.csdn.net/topics/390890082,觉得挺好的,保存下来

获取在ListBox中的DataTemplate下的每一个button对象的方法如下:
 private T SearchVisualTree(DependencyObject tarElem) where T : DependencyObject
        {
            if (tarElem != null)
            {
                var count = VisualTreeHelper.GetChildrenCount(tarElem);
                if (count == 0)
                    return null;
                for (int i = 0; i                  {
                    var child = VisualTreeHelper.GetChild(tarElem, i);
                    if (child != null && child is T)
                    {
                        return (T)child;
                    }
                    else
                    {
                        var res = SearchVisualTree(child);
                        if (res != null)
                        {
                            return res;
                        }
                    }
                }
                return null;
            }
   private void GetBtn()
        {
            for (int i = 0; i              {
                ListBoxItem itemtemp = this.ListBoxName.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                Button buttonobject = SearchVisualTree

WPF 查找ListBox等DataTemplate下的子控件

标签:children   item   top   ems   break   where   help   temp   好的   

原文地址:http://www.cnblogs.com/Liang-Xiang/p/7728017.html


评论


亲,登录后才可以留言!