.NET/C# Get First Visible Item of a ListBox

This is some code to get the first visible item in a WPF ListBox whenever the user scrolled.

In XAML:

<ListBox Name="MyListBox" 
  ItemsSource="{Binding SomeCollection}" 
  ScrollViewer.ScrollChanged="ScrollChanged"/>

In the code-behind:

private void ScrollChanged(object sender, ScrollChangedEventArgs e)
{
  VirtualizingStackPanel panel = FindVisualChild<VirtualizingStackPanel>(MyListBox);
  if (MyListBox.Items.Count > 0 && Panel != null)
  {
    int offset = 
      (panel.Orientation == Orientation.Horizontal) ? (int)panel.HorizontalOffset : (int)panel.VerticalOffset;
    var item = MyListBox.Items[offset];
  }
}

Some helper code to get hold of the ListBox’s panel:

private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  {
    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
 
    if (child is T)
    {
      return (T)child;
    }
    else
    {
      child = FindVisualChild<T>(child);
      if (child != null)
      {
        return (T)child;
      }
    }
  }
  return null;
}

4 thoughts on “.NET/C# Get First Visible Item of a ListBox

Comments are closed.