I wanted to add a scroll down prompt to ScrollView in my Xamarin app, for which I followed this article.
What it actually does is that it adds a scroll down indicator (Label) outside Scrollview, so if the text is more than the size of the page it shows this indication, written "Scroll down for more!", and when scrolling completely to the end, it hides this indicator.
This part is working, but if the text is less than the page, it still shows this scroll down indicator.
I want that if the text is less than the page, the visibility of the scroll down indicator should be false.
.xaml
<Grid>
<ScrollView x:Name="MyScrollView" Scrolled="MyScrollView_Scrolled">
<StackLayout>
<BoxView BackgroundColor="Red" HeightRequest="128"/>
<BoxView BackgroundColor="Orange" HeightRequest="128"/>
</StackLayout>
</ScrollView>
<Label x:Name="ScrollDownIndicator"
Text="Scroll down for more!"
BackgroundColor="Black"
TextColor="White"
FontSize="Large"
HorizontalTextAlignment="Center"
VerticalOptions="End"/>
</Grid>
.xaml.cs
private void MyScrollView_Scrolled(object sender, ScrolledEventArgs e)
{
double spaceAvailableForScrolling = MyScrollView.ContentSize.Height - MyScrollView.Height;
double buffer = 32;
ScrollDownPrompt.IsVisible = spaceAvailableForScrolling > e.ScrollY buffer;
}
CodePudding user response:
Juggling around with your code i came to a solution that might get you where you want.
Just looking for the fix? go and read Solution section. If you want to know the why, go ahead and read the Explanation section.
Solution
First of all, i realized that in the code you posted the Label
in Xaml file is called ScrollDownIndicator
, but in the event handler you are changing a variable called ScrollDownPrompt
instead. On my tests i went ahead to equalize both names...
In your .xaml.cs file, add the following lines to your page constructor:
public MainPage()
{
InitializeComponent();
MyScrollView.PropertyChanged = (s, a) =>
{
if (a.PropertyName == ScrollView.ContentSizeProperty.PropertyName)
{
double buffer = 32;
double spaceAvailableForScrolling = MyScrollView.ContentSize.Height - MyScrollView.Height;
ScrollDownIndicator.IsVisible = spaceAvailableForScrolling > buffer;
}
};
}
private void MyScrollView_Scrolled(object sender, ScrolledEventArgs e)
{
double spaceAvailableForScrolling = MyScrollView.ContentSize.Height - MyScrollView.Height;
double buffer = 32;
ScrollDownPrompt.IsVisible = spaceAvailableForScrolling > e.ScrollY buffer;
}
Explanation
In your code you only change the visibility of the Indicator from the event handler: MyScrollView_Scrolled
. If no scrolling is performed, the event handler is not called and no visibility of the indicator is checked: it is simply always visible.
To correct this behavior you have to check the visibility when the ContentSize property of ScrollView changes.
Hope this helps some people :D