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

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

相关推荐
freewlt2 分钟前
Rust在前端工具链的崛起:2026年生态全景
开发语言·前端·rust
Java面试题总结10 分钟前
Java常见面试题(160道)
java·开发语言
Rsun0455113 分钟前
7、Java 装饰器模式从入门到实战
java·开发语言·装饰器模式
fengci.16 分钟前
php反序列化(复习)(第五章)
android·开发语言·学习·php
AI瓦力17 分钟前
PDFBox处理JPEG2000图像报错解决方案(PDF扫描件)
开发语言
深邃-18 分钟前
【C语言】-自定义类型:结构体
c语言·开发语言·数据结构·c++·html5
秋月的私语19 分钟前
遥感影像拼接线优化工具:基于Qt+GDAL+OpenCV的从二到三实践
开发语言·qt·opencv
cmpxr_20 分钟前
【C】结构体的内存对齐
c语言·开发语言·算法
李松桃25 分钟前
音乐爬虫 - Python
开发语言·python·python实操
Rsun0455127 分钟前
9、Java 外观模式从入门到实战
java·开发语言·外观模式