码迷,mamicode.com
首页 > Windows程序 > 详细

WPF 查找控件的所有子控件

时间:2018-05-09 10:51:25      阅读:830      评论:0      收藏:0      [点我收藏+]

标签:where   summary   void   public   etc   oid   efault   help   列表   

        /// <summary>
        /// 查找子控件
        /// </summary>
        /// <typeparam name="T">控件类型</typeparam>
        /// <param name="parent">父控件依赖对象</param>
        /// <param name="lstT">子控件列表</param>
        public static void FindVisualChild<T>(DependencyObject parent, ref List<T> lstT) where T : DependencyObject
        {
            if (parent != null)
            {
                T child = default(T);
                int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < numVisuals; i++)
                {
                    Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                    child = v as T;
                    if (child != null)
                    {
                        lstT.Add(child);
                    }
                    FindVisualChild<T>(v, ref lstT);
                }
            }
        }

在DataGrid中查找选定行中的子控件使用实例:

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGridRow currentRow = (DataGridRow)dgdRel.ItemContainerGenerator.ContainerFromIndex(dgdRel.SelectedIndex);   //获取当前行
            if (currentRow != null)
            {
                List<Control> lstControl = new List<Control>();
                FormDispose.FindVisualChild<Control>(currentRow, ref lstControl);  //获取当前行内所有的控件
                if (lstControl != null)
                {
                   //子控件的处理代码
                }
            }
        }

 

WPF 查找控件的所有子控件

标签:where   summary   void   public   etc   oid   efault   help   列表   

原文地址:https://www.cnblogs.com/yilinyangyu/p/9012748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!