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

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

相关推荐
The hopes of the whole village4 分钟前
matlab 绘图
开发语言·matlab·信息可视化
蔗理苦13 分钟前
2025-04-24 Python&深度学习4—— 计算图与动态图机制
开发语言·pytorch·python·深度学习·计算图
[太阳]8819 分钟前
Kafka命令行的使用/Spark-Streaming核心编程(二)
c#·linq
Mr Aokey2 小时前
手写Java线程池与定时器:彻底掌握多线程任务调度
java·开发语言
✿ ༺ ོIT技术༻3 小时前
笔试强训:Day2
开发语言·c++·笔记·算法
Jackson@ML4 小时前
如何快速高效学习Python?
开发语言·python
西瓜本瓜@6 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
UFIT6 小时前
Python函数与模块笔记
开发语言·python
机智的人猿泰山6 小时前
java kafka
java·开发语言·kafka
Y1nhl6 小时前
搜广推校招面经八十一
开发语言·人工智能·pytorch·深度学习·机器学习·推荐算法·搜索算法