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

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

相关推荐
xxjj998a5 小时前
Laravel3.x:奠定现代PHP框架的重要里程碑
android·开发语言·php
(Charon)5 小时前
【C++/Qt】Qt 实现 MQTT 测试工具:连接 Broker、订阅主题与发布消息
开发语言·c++·qt
Ulyanov5 小时前
《现代 Python 桌面应用架构实战:PySide6 + QML 从入门到工程化》:动态数据仪表盘与 NumPy 可视化 —— 从标量到向量的数据驱动进化
开发语言·python·qt·架构·numpy
小短腿的代码世界5 小时前
Qt序列化与持久化深度解析:从QDataStream到自定义二进制协议
开发语言·数据库·qt
周末也要写八哥6 小时前
Golang语言与Rust语言的对比
开发语言·后端·golang
楼田莉子6 小时前
Linux网络:数据链路层
linux·服务器·开发语言·网络·c++·后端
不甘先生6 小时前
Go 四层架构实战:Handler + Service + Repository + Entity(清晰、可控、可演进)
开发语言·架构·golang
Yang-Never6 小时前
Git -> Git Worktree 工作树
android·开发语言·git·android studio
riNt PTIP6 小时前
GO 快速升级Go版本
开发语言·redis·golang
xingpanvip6 小时前
星盘接口开发文档:日运语料接口指南
android·开发语言·前端·css·php·lua