How to get ListBox ItemsPanel in code behind

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

I have a ListBox with an ItemsPanel


    
        
             

        
3条回答
  •  渐次进展
    2020-12-17 16:55

    You can use the Loaded event for the StackPanel that is in the ItemsPanelTemplate

    
        
            
        
        
    
    

    And then in code behind

    private StackPanel m_itemsPanelStackPanel;
    private void StackPanel_Loaded(object sender, RoutedEventArgs e)
    {
        m_itemsPanelStackPanel = sender as StackPanel;
    }
    

    Another way is to traverse the Visual Tree and find the StackPanel which will be the first child of the ItemsPresenter.

    public void SomeMethod()
    {
        ItemsPresenter itemsPresenter = GetVisualChild(listBox);
        StackPanel itemsPanelStackPanel = GetVisualChild(itemsPresenter);
    }
    
    private static T GetVisualChild(DependencyObject parent) where T : Visual
    {
        T child = default(T);
    
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }
    

提交回复
热议问题