Search code examples
c#xamlscrollviewscrollbarwinui-3

How to scroll the contents of the ScrollViewer using my own ScrollBar?


I have a ScrollBar and a ScrollViewer.
I want to scroll the contents of the ScrollViewer using my own ScrollBar.

This is my code:

<StackPanel HorizontalAlignment="Stretch">
    <ScrollBar
        x:Name="TestScrollBar"
        HorizontalAlignment="Stretch"
        Orientation="Horizontal"
        Scroll="TestScrollBar_Scroll"
        Maximum="{Binding ElementName=TestScrollViewer, Path=ExtentWidth, Mode=OneWay}"
        ViewportSize="{Binding ElementName=TestScrollViewer, Path=ViewportWidth, Mode=OneWay}"
        Visibility="Visible"
        Background="Aqua"/> <!--This is set for seeing when/if the ScrollBar is visible-->
    <ScrollViewer
        x:Name="TestScrollViewer"
        ViewChanged="TestScrollViewer_ViewChanged"
        HorizontalAlignment="Stretch"
        HorizontalScrollMode="Auto"
        HorizontalScrollBarVisibility="Auto"> <!--This is set to Auto for now, but should be Disabled/Hidden later-->
        <TextBlock FontSize="144" Text="This is blind text. Ignore this completely. It is only here to fill up the ScrollViewer horizontally."/>
    </ScrollViewer>
</StackPanel>
private void TestScrollBar_Scroll(object sender, ScrollEventArgs e)
{
    TestScrollViewer.ChangeView(e.NewValue, null, null);
}

private void TestScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
    TestScrollBar.Value = TestScrollViewer.HorizontalOffset;
}

When I run my app, the Bar is visible for a few milliseconds (a aqua-colored flash) and disappears after.
I checked all the values that are set in XAML and my code using the Live Visual Tree and Live Property Explorer, but the ScrollBar isn't visible, even when the one of the ScrollViewer is.


Solution

  • You just need to set IndicatorMode to MouseIndicator. The IndicatorMode is None by default.

    So, your ScrollBar code should be like this:

    <ScrollBar
        x:Name="TestScrollBar"
        HorizontalAlignment="Stretch"
        Background="Aqua"
        IndicatorMode="MouseIndicator"
        Maximum="{Binding ElementName=TestScrollViewer, Path=ExtentWidth, Mode=OneWay}"
        Orientation="Horizontal"
        Scroll="TestScrollBar_Scroll"
        ViewportSize="{Binding ElementName=TestScrollViewer, Path=ViewportWidth, Mode=OneWay}"
        Visibility="Visible" />