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

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

相关推荐
aq553560015 小时前
编程语言三巨头:汇编、C++与PHP大比拼
java·开发语言
aq553560015 小时前
PHP vs Python:30秒看懂核心区别
开发语言·python·php
我是无敌小恐龙15 小时前
Java SE 零基础入门Day01 超详细笔记(开发前言+环境搭建+基础语法)
java·开发语言·人工智能·opencv·spring·机器学习
码云数智-大飞16 小时前
零基础微信小程序制作平台哪个好
开发语言
神仙别闹16 小时前
基于 MATLAB 实现的 DCT 域的信息隐藏
开发语言·matlab
techdashen17 小时前
Go 标准库 JSON 包迎来重大升级:encoding/json/v2 实验版来了
开发语言·golang·json
.千余17 小时前
【Linux】基本指令3
linux·服务器·开发语言·学习
南境十里·墨染春水17 小时前
C++ 笔记 thread
java·开发语言·c++·笔记·学习
南境十里·墨染春水17 小时前
C++ 笔记 高级线程同步原语与线程池实现
java·开发语言·c++·笔记·学习
来自远方的老作者18 小时前
第10章 面向对象-10.4 继承
开发语言·python·继承·单继承·多继承·super函数