Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>All you need to do is to get the underlying StackPanel that's inside the ListBox. It has enough information about which elements are showing. (It implements the interface IScrollInfo).</p> <p>To get the underlying StackPanel (or actually VirtualizingStackPanel) from a given ListBox, we'll have to use VisualTreeHelper to go through the Visual Tree and look for the VirtualizingStackPanel, like so:</p> <pre><code> private VirtualizingStackPanel GetInnerStackPanel(FrameworkElement element) { for (int i = 0; i &lt; VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement; if (child == null) continue; Debug.WriteLine(child.ToString()); if (child is VirtualizingStackPanel) return child as VirtualizingStackPanel; var panel = GetInnerStackPanel(child); if (panel != null) return panel; } return null; } </code></pre> <p>Now that we have the StackPanel, we're very close. The StackPanel has the properties <code>VerticalOffset</code> and <code>ViewportHeight</code> (both coming from <code>IScrollInfo</code>) that can give us all the information we need.</p> <pre><code> private void button1_Click(object sender, RoutedEventArgs e) { var theStackPanel = GetInnerStackPanel(MyListBox); List&lt;FrameworkElement&gt; visibleElements = new List&lt;FrameworkElement&gt;(); for (int i = 0; i &lt; theStackPanel.Children.Count; i++) { if (i &gt;= theStackPanel.VerticalOffset &amp;&amp; i &lt;= theStackPanel.VerticalOffset + theStackPanel.ViewportHeight) { visibleElements.Add(theStackPanel.Children[i] as FrameworkElement); } } MessageBox.Show(visibleElements.Count.ToString()); MessageBox.Show(theStackPanel.VerticalOffset.ToString()); MessageBox.Show((theStackPanel.VerticalOffset + theStackPanel.ViewportHeight).ToString()); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload