简体   繁体   中英

WPF ScrollViewer horizontal scrolling with buttons

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM