TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

Scroll a ListBox's VirtualizingStackPanel with buttons

I have a Listbox displaying 5 items at a time, horizontally. I want to implement a 'Previous' and 'Next' button that when clicked, will display the previous set of 5, or next set of 5 items. I am not displaying the horizontal scroll bar, as I don't want a user to navigate with that.

Is there already some functionality implemented so I can do this, or do I need to write code to calculate what items I'm displaying, etc, in the button's click events?

Thanks in advance!

Upvotes: 1

Views: 809

Answers (2)

Ray Burns
Ray Burns

Reputation: 62919

You can use the built-in ScrollViewer.PageUp() and ScrollViewer.PageDown() commands, like this:

public void ShowNextPage()
{
   InvokeOnScrollViewer(listBox, viewer => viewer.PageDown());
}

public void ShowPriorPage()
{
   InvokeOnScrollViewer(listBox, viewer => viewer.PageUp());
}

public void InvokeOnScrollViewer(ItemsControl control, Action<ScrollViewer> action)
{
  for(Visual vis = control as Visual; VisualTreeHelper.GetChildCount(vis)!=0; vis = VisualTreeHelper.GetChild(vis, 0))
    if(vis is ScrollViewer)
    {
      Action((ScrollViewer)vis);
      break;
    }
}

How it works: InvokeOnScrollViewer scans down the visual tree until it finds the ScrollViewer, then invokes the given action on it, which is either PageUp() or PageDown().

When your ItemsPanel is a StackPanel (of either orientation, virtualizing or not), ScrollViewer.PageUp() moves back by one viewport and ScrollViewer.PageDown() moves forward by one viewport. In other words, if your ListBox shows five items then these commands move it by five items.

Upvotes: 1

Anvaka
Anvaka

Reputation: 15823

Look at ListBox.ScrollIntoView() method.

Upvotes: 0

Related Questions