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;
}
Permalink