Find all controls in WPF Window by type

后端 未结 17 1229
春和景丽
春和景丽 2020-11-21 10:14

I\'m looking for a way to find all controls on Window by their type,

for example: find all TextBoxes, find all controls implementing specific i

17条回答
  •  余生分开走
    2020-11-21 10:48

    And this is how it works upwards

        private T FindParent(DependencyObject item, Type StopAt) where T : class
        {
            if (item is T)
            {
                return item as T;
            }
            else
            {
                DependencyObject _parent = VisualTreeHelper.GetParent(item);
                if (_parent == null)
                {
                    return default(T);
                }
                else
                {
                    Type _type = _parent.GetType();
                    if (StopAt != null)
                    {
                        if ((_type.IsSubclassOf(StopAt) == true) || (_type == StopAt))
                        {
                            return null;
                        }
                    }
    
                    if ((_type.IsSubclassOf(typeof(T)) == true) || (_type == typeof(T)))
                    {
                        return _parent as T;
                    }
                    else
                    {
                        return FindParent(_parent, StopAt);
                    }
                }
            }
        }
    

提交回复
热议问题