0
votes

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.

1
"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
@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

1 Answers

0
votes

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);
}