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

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

相关推荐
kyle~2 分钟前
C++--- dlsym 调用封装好的算法动态库的核心工具 <dlfcn.h>
开发语言·c++·算法
一晌小贪欢2 分钟前
Python办公自动化指南:Pandas与Openpyxl的全面比较与选择
开发语言·python·pandas·python基础·python入门·python小白
于先生吖6 分钟前
2026 新版上门回收系统源码 JAVA 同城服务平台搭建指南
java·开发语言
似水明俊德12 分钟前
12-C#.Net-加密解密-学习笔记
笔记·学习·oracle·c#·.net
MX_935916 分钟前
Spring整合Web环境实现思路
java·开发语言·后端·spring
C羊驼19 分钟前
C语言学习笔记(十四):编译与链接
c语言·开发语言·经验分享·笔记·学习
阿蒙Amon19 分钟前
C#常用类库-详解SSH.NET
c#·ssh·.net
似水明俊德23 分钟前
11-C#.Net-多线程-Async-Await篇-学习笔记
开发语言·笔记·学习·c#·.net
Byron__23 分钟前
ArrayList 与 LinkedList 源码深度对比解析
java·开发语言
Irissgwe27 分钟前
线程概念与控制
linux·开发语言·c++·线程