How to get ListBox ItemsPanel in code behind

后端 未结 3 888
心在旅途
心在旅途 2020-12-17 16:20

I have a ListBox with an ItemsPanel


    
        
             

        
3条回答
  •  心在旅途
    2020-12-17 16:55

    Try out following extension method:

    var childStackPanels = FindVisualChildren(ThumbListBox);
    

    Method itself:

    public static IEnumerable FindVisualChildren(this DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                var typedChild = child as T;
                if (typedChild != null)
                {
                    yield return typedChild;
                }    
    
                foreach (T childOfChild in FindVisualChildren(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
    

    PS: You can yourself extend it to check for specific control name so method would return single control instead of list.

提交回复
热议问题