[原] c# winform controls 查找指定類型子控件的擴展方法


//調用
this.Controls.Find<Button>(true).ForEach((btn) => { btn.Enabled = false; });


//定義
public static class FormControlExtensions
    {
        /// <summary>
        /// 獲得指定類型的孩子控件
        /// </summary>
        /// <typeparam name="TChild">子控件類型</typeparam>
        /// <param name="controlCollection"></param>
        /// <param name="searchAllChildren">如果搜索所有子控件,則為 true;否則為 false。默認為false。</param>
        /// <returns></returns>
        public static List<TChild> Find<TChild>(this Control.ControlCollection controlCollection, bool searchAllChildren = false) 
            where TChild : Control
        {
            var children = new List<TChild>();
            _Find(controlCollection, ref children, searchAllChildren);
            return children;
        }

        /// <summary>
        /// 查詢指定類型的子控件(支持遞歸)
        /// </summary>
        /// <typeparam name="TChild">子控件類型</typeparam>
        /// <param name="controlCollection"></param>
        /// <param name="children"></param>
        /// <param name="searchAllChildren">如果搜索所有子控件,則為 true;否則為 false。默認為false。</param>
        private static void _Find<TChild>(Control.ControlCollection controlCollection, ref List<TChild> children, bool searchAllChildren = false) 
            where TChild : Control
        {
            foreach (Control control in controlCollection)
            {
                if (control is TChild)
                {
                    children.Add((TChild)control);
                }

                if (control.Controls.Count > 0 && searchAllChildren)
                {
                    _Find(control.Controls, ref children, searchAllChildren);
                }
            }
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM