views:

31

answers:

2

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!

A: 

Look at ListBox.ScrollIntoView() method.

Anvaka
Was looking for something like DisplayNext() or something already implemented - in case I was overlooking something really simple. I was going to implement ScrollIntoView but wanted to make sure before I did. Thanks for the answer.
TheGeekYouNeed
This answer is wrong, or at the very least misleading. You can use ScrollViewer.PageUp() and ScrollViewer.PageDown() to do exactly what you're asking for. I just wrote an answer that explains how.
Ray Burns
Hold on Ray. Why do you say it's wrong? It's more general yes, but it's not wrong.
Anvaka
Ray's answer is the kind of functionality I was looking for.
TheGeekYouNeed
+1  A: 

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.

Ray Burns
Hi Ray, I'm using this implementation with a new question I have here http://stackoverflow.com/questions/3098383/previewmouseleftbuttondown-not-firing -- Would like to pick your brain to see if you have any ideas about why I'm having some problems. Thanks again for the help thus far!
TheGeekYouNeed