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.小结

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

相关推荐
网域小星球2 分钟前
C++ 从 0 入门(二)|引用与指针区别、函数重载、内联函数(面试高频)
开发语言·c++·面试·函数重载·内联函数·引用与指针区别
代码中介商9 分钟前
C++ 多态与虚函数入门:从概念到规则
开发语言·c++
kyle~16 分钟前
工业以太网协议---EtherCAT
开发语言·c++·网络协议·机器人·ros2
say_fall21 分钟前
深入理解AVL树:平衡调整机制与性能优化实战
开发语言·数据结构·c++·学习
赖在沙发上的熊24 分钟前
Python数据序列
开发语言·python
Hello--_--World30 分钟前
Js面试题目录表
开发语言·javascript·ecmascript
聆风吟º30 分钟前
【C标准库】深入理解C语言strcmp函数:字符串比较的核心用法
c语言·开发语言·库函数·strcmp
Fanfanaas36 分钟前
Linux 进程篇 (四)
linux·运维·服务器·开发语言·c++·学习
Sylvia-girl37 分钟前
C++中类与对象
开发语言·c++
良木生香40 分钟前
【C++初阶】:泛型编程的代表作---C++初阶模板
c语言·开发语言·数据结构·c++·算法