0

I have a ListBox with horizontal orientation inside a ScrollViewer. When the list grows, it automatically scrolls to the last element. The scrollbars work, however must be disabled for this. I need to have separate buttons which would scroll the ScrollViewer by a predetermined iteration (much like buttons on the scrollbars). For this, I have tried:

sv.ScrollToHorizontalOffset(sv.HorizontalOffset + 20);

However, the ScrollViewer's HorizontalOffset seems to always be 0, and the method doesn't do anything with any values.

sv.LineRight();
sv.LineLeft();

both don't work, probably because the only child element is the ListBox. If I change the ListBox's orientation to vertical, then the ScrollViewer's VerticalOffset changes with scrolling/adding new elements, and ScrollToVerticalOffset works correctly. Why is this different with horizontal orientation? Any other solutions?

Note: this was done without using XAML to place the controls.

u17
  • 3
  • 2
  • "*ListBox ... inside a ScrollViewer*" does not seem to make sense in the first place. ListBox already supports scrolling. And it has a ScrollIntoView method. – Clemens Sep 18 '20 at 09:44
  • @Clemens thank you, but the idea is that I need to move the scrolling position by a set number of pixels, not just scroll to an item. – u17 Sep 18 '20 at 10:23

1 Answers1

0

To make this work, you need to do a couple things:

Remove the outer ScrollViewer and just use the ScrollViewer that is built into the ListBox.

On the ListBox set the following properties:

ScrollViewer.CanContentScroll="False"

This will make the HorizontalOffset property work in pixels. When it is set to True it works in items.

ScrollViewer.HorizontalScrollBarVisibility="Hidden"

This will keep scrolling active but will hide the scrollbar.

In your code you can get the ScrollViewer of the ListBox like so. In this example my ListBox is named x:Name="ListBox".

var scrollViewer = ListBox.FindChildByType<ScrollViewer>();

Finally, you can set the offset like below. In my sample, I created a method and passed in a value from my button click event handlers.

private void ScrollHorizontally(double offset)
{
    var scrollViewer = ListBox.FindChildByType<ScrollViewer>();

    scrollViewer?.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + offset);
}
Keithernet
  • 2,349
  • 1
  • 10
  • 16
  • My ListBox does not contain a method "FindChildByType". Are you using a library of some sort? – u17 Sep 21 '20 at 08:23
  • This answer has a method you could use: https://stackoverflow.com/questions/10279092/how-to-get-children-of-a-wpf-container-by-type – Keithernet Sep 21 '20 at 17:03