Smooth scroll within stackpanel in wpf

2020-06-04 12:32发布

<ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True">
                <StackPanel Name="basePanel" Orientation="Vertical" Height="450" />
            </ScrollViewer>

This is the code for the stackpanel which is filled in runtime with multiple WrapPanels. Scroll Viewer scrolls through the panels - one at a time - which makes it really inconvenient because all panels are of different sizes. I tried this one by setting ScrollViewer.CanContentScroll="False" property in StackPanel while deleting it in ScrollViewer, didn't help - scroll bar disappeared at all. What's the solution for smooth scroll bar?

1条回答
Evening l夕情丶
2楼-- · 2020-06-04 12:57

Wrap your StackPanel in another panel

WPF's ScrollViewer tries to scroll entire elements into view at a time, which is why you see the jumpy scroll behavior. By nesting the StackPanel in another Panel, the ScrollViewer will try and scroll the entire StackPanel into view, which is too big so it will use smooth scrolling.

Here's an example - Removing the DockPanel will give you a jumpy scroll, but with it you'll get smooth scrolling behavior

<ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True" Height="250">
    <DockPanel>
        <StackPanel Name="basePanel" Orientation="Vertical" Width="200">
            <Rectangle Height="75" Fill="Red" Width="200" />
            <Rectangle Height="50" Fill="Orange" Width="200" />
            <Rectangle Height="75" Fill="Yellow" Width="200" />
            <Rectangle Height="75" Fill="Green" Width="200" />
            <Rectangle Height="75" Fill="Black" Width="200"  />
            <Rectangle Height="75" Fill="Purple" Width="200" />
        </StackPanel>
    </DockPanel>
</ScrollViewer>
查看更多
登录 后发表回答