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 分钟前
计算机是如何⼯作的
linux·开发语言·python
weixin_520649877 分钟前
C#闭包知识点详解
开发语言·c#
东北甜妹11 分钟前
Redis Cluster 操作命令
java·开发语言
花间相见13 分钟前
【大模型微调与部署01】—— ms-swift-3.12入门:安装、快速上手
开发语言·ios·swift
techdashen21 分钟前
Rust 正式成立 Types Team:类型系统终于有了专属团队
开发语言·后端·rust
jiayong2324 分钟前
第 17 课:任务选择与批量操作
开发语言·前端·javascript·vue.js·学习
量子炒饭大师33 分钟前
【C++11】RAII 义体加装指南 ——【包装器 与 异常】C++11中什么是包装器?有哪些包装器?C++常见异常有哪些?(附带完整代码讲解)
开发语言·c++·c++11·异常·包装器
telllong36 分钟前
Python异步编程从入门到不懵:asyncio实战踩坑指南
开发语言·python
知兀37 分钟前
【Result类】(使用/不使用<T> data的情况);自带静态方法、纯数据类;
java·开发语言
达帮主38 分钟前
25.C语言 递归函数
c语言·开发语言·汇编