Looping over XAML defined labels

后端 未结 6 1299
傲寒
傲寒 2021-01-18 08:58

I have a WPF application with many labels.

         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 09:28

    Using this code

    public static IEnumerable FindVisualChildren(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(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
    

    You can enumerate all controls by type.

    foreach (Label lbl in FindVisualChildren

提交回复
热议问题