How can I find WPF controls by name or type?

后端 未结 18 3003
庸人自扰
庸人自扰 2020-11-21 04:23

I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?

18条回答
  •  鱼传尺愫
    2020-11-21 05:00

    I have a sequence function like this (which is completely general):

        public static IEnumerable SelectAllRecursively(this IEnumerable items, Func> func)
        {
            return (items ?? Enumerable.Empty()).SelectMany(o => new[] { o }.Concat(SelectAllRecursively(func(o), func)));
        }
    

    Getting immediate children:

        public static IEnumerable FindChildren(this DependencyObject obj)
        {
            return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(obj))
                .Select(i => VisualTreeHelper.GetChild(obj, i));
        }
    

    Finding all children down the hiararchical tree:

        public static IEnumerable FindAllChildren(this DependencyObject obj)
        {
            return obj.FindChildren().SelectAllRecursively(o => o.FindChildren());
        }
    

    You can call this on the Window to get all controls.

    After you have the collection, you can use LINQ (i.e. OfType, Where).

提交回复
热议问题