How do I access the ItemsPresenter of a ListBox?

Platform: WPF| Category: ItemsControl

This same logic can be used to access the ItemsPresenter of other ItemsControls like ListView, etc.

[C#]
public partial class RetrieveItemsPanelDemo : Window
{
    public RetrieveItemsPanelDemo()
    {
        InitializeComponent();
        ListBox listBox = new ListBox() { ItemsSource = Enumerable.Range(0, 10) };
        this.Content = listBox;
        listBox.Loaded += delegate
        {
            VirtualizingStackPanel itemsPanel = listBox.GetVisualChild();
            if (itemsPanel != null && itemsPanel.IsItemsHost)
            {
                itemsPanel.PreviewMouseLeftButtonDown += delegate { MessageBox.Show('WPF'); };
            }
        };
    }
}

public static T GetVisualChild(this Visual referenceVisual) where T : Visual
{
    Visual child = null;
    for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceVisual); i++)
    {
        child = VisualTreeHelper.GetChild(referenceVisual, i) as Visual;
        if (child != null && (child.GetType() == typeof(T)))
        {
            break;
        }
        else if (child != null)
        {
            child = GetVisualChild(child);
            if (child != null && (child.GetType() == typeof(T)))
            {
                break;
            }
        }
    }
    return child as T;
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.