views:

640

answers:

2

I had an ItemsControl, which you could use page up/down buttons to scroll expectedly. I switched it with a ListBox, to apply (thru triggers) a new DataTemplate when an item is selected.

Everything works fine, until using pageup or pagedown buttons. Instead of scrolling one page, it scrolls till the end or the beginning.

My previous attemps:

  • Not changing the item height when DataTemplate changes
  • Removed IsSelected=True trigger completely
  • All SelectionMode values

Do I miss something trivial?

A: 

Indeed, I missed something trivial. I forgot to remove the ScrollViewer outside the ItemsControl. I guess, this creates a confusion, since ListBox has its own ScrollViewer.

This raised another question. Previous ScrollViewer were automaticcally scrolled down from code behind. Now, that I can't reach the ListBox's ScrollViewer, I can't call its LineDown method. Here is my workaround:

// Responses is the ItemsSource
Responses.Add(e); 
// xResponses is the ListBox
var item = xResponses.ItemContainerGenerator.ContainerFromIndex(0);
ScrollBar.LineDownCommand.Execute(null, item as IInputElement);

In the beginning, item might evaluate to null, however this does not create a problem. After adding a few items, luckily before we need to scroll, a container is returned successfully. Note that index is not important here, all we need is an IInputElement inside the ScrollViewer.

orca
A: 
private void RaiseKeyDownUpEventsOnEntitiesBox(Key key)
{
    KeyEventArgs keyEventArgs = new KeyEventArgs(
        InputManager.Current.PrimaryKeyboardDevice,   
        Keyboard.PrimaryDevice.ActiveSource, 
        System.Environment.ProcessorCount, key);
    keyEventArgs.RoutedEvent = UIElement.KeyDownEvent; 
    entitiesBox.RaiseEvent(keyEventArgs);
    keyEventArgs.RoutedEvent = UIElement.KeyUpEvent; 
    entitiesBox.RaiseEvent(keyEventArgs);
}

Page Down

RaiseKeyDownUpEventsOnEntitiesBox(Key.Next);

Page Up

RaiseKeyDownUpEventsOnEntitiesBox(Key.Prior);