I have a ListBox with an ItemsPanel
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;
}