C#--WPF遍循ListBox子控件

1.代码部分

cs 复制代码
        //Listbox--Name wList
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            BoatIdVM.Instance.Active(null);
            if (Setting5VM.Instance.DicCanExecute["BoatID33"](null))
            {
                DG.IsReadOnly = false;
                for (int i = 0; i < wList.Items.Count; i++)
                {
                    var itemContainer = wList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                    if (itemContainer != null)
                    {
                        var button = FindVisualChild<Button>(itemContainer);
                        if (button != null)
                        {
                            button.IsEnabled = true;
                        }
                    }
                }
            }
            else
            {
                DG.IsReadOnly = true;//只读

                for (int i = 0; i < wList.Items.Count; i++)
                {
                    var itemContainer = wList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                    if (itemContainer != null)
                    {
                        var button = FindVisualChild<Button>(itemContainer);
                        if (button != null)
                        {
                            button.IsEnabled = false;
                        }
                    }
                }
            }
        }

        // FindVisualChild方法用于在VisualTree中查找指定类型的子元素
        private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T typedChild)
                {
                    return typedChild;
                }

                var result = FindVisualChild<T>(child);
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }

2.小结

上述代码完成对于可视化树下面子控件的遍历,日常使用记录

相关推荐
结衣结衣.5 分钟前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
学习使我变快乐7 分钟前
C++:静态成员
开发语言·c++
TJKFYY7 分钟前
Java.数据结构.HashSet
java·开发语言·数据结构
杰哥在此16 分钟前
Python知识点:如何使用Multiprocessing进行并行任务管理
linux·开发语言·python·面试·编程
小白学大数据16 分钟前
User-Agent在WebMagic爬虫中的重要性
开发语言·爬虫·http
ROBIN__dyc22 分钟前
C语言基本概念
c语言·开发语言
学习使我变快乐2 小时前
C++:const成员
开发语言·c++
500了3 小时前
Kotlin基本知识
android·开发语言·kotlin
不知所云,5 小时前
qt cmake自定义资源目录,手动加载资源(图片, qss文件)
开发语言·qt
安冬的码畜日常6 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine