开发者

Can I create an extension method for a WPF UserControl that can return a list of its controls?

开发者 https://www.devze.com 2023-02-15 07:48 出处:网络
Is this possible while the controls are not publicly exposed through proper开发者_StackOverflow社区ties ?this is easy to achive: (code from this SO question)

Is this possible while the controls are not publicly exposed through proper开发者_StackOverflow社区ties ?


this is easy to achive: (code from this SO question)

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}


If a control is part of the Visual Tree of that UserControl, then yes, you can list all the visual children of that control. And you can wrap that logic in an extension method.

You can use VisualTreeHelper class for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号