Based on the images and your description, I thought your purpose is to create a button which is used to let a ScrollViewer
scroll to the top. The problem is how to let the button display when the ScrollViewer’s
content is not at the bottom whenever you scroll up or down the bar or resize the window, and hide the button when when the ScrollViewer’s
content is not at the bottom whenever you scroll up or down the bar or resize the window.
You could use VerticalOffset property which represents the distance the content has been scrolled vertically and ViewportHeight property which represents the vertical size of the viewable content and ExtentHeight property which represents the vertical size of all the scrollable content in the ScrollViewer
, to determine whether the content of the ScrollViewer
reach the bottom.
Please check the following code as a sample:
//MainPage.xaml
<Grid SizeChanged="Grid_SizeChanged">
<ScrollViewer x:Name="scrollViewer" VerticalScrollBarVisibility="Visible" VerticalScrollMode="Enabled"
ViewChanged="scrollViewer_ViewChanged">
<StackPanel x:Name="stackPanel" Background="LightGray">
<TextBlock Text="0" Margin="20"/>
<TextBlock Text="1" Margin="20"/>
<TextBlock Text="2" Margin="20"/>
<TextBlock Text="3" Margin="20"/>
<TextBlock Text="4" Margin="20"/>
<TextBlock Text="5" Margin="20"/>
<TextBlock Text="6" Margin="20"/>
<TextBlock Text="7" Margin="20"/>
<TextBlock Text="8" Margin="20"/>
<TextBlock Text="9" Margin="20"/>
<TextBlock Text="10" Margin="20"/>
<TextBlock Text="11" Margin="20"/>
<TextBlock Text="12" Margin="20"/>
</StackPanel>
</ScrollViewer>
<Button x:Name="BackButton" Content="top" Click="BackButton_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
</Grid>
//MainPage.xaml.cs
private void BackButton_Click(object sender, RoutedEventArgs e)
{
//The code is used to scroll to the top
scrollViewer.ChangeView(null, 0, null);
//the code is used to scroll to the bottom
//scrollViewer.ChangeView(null, scrollViewer.ExtentHeight-scrollViewer.ViewportHeight, null);
}
private void scrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var verticalOffset = scrollViewer.VerticalOffset;
var extentHeight = scrollViewer.ExtentHeight;
var viewportHeight = scrollViewer.ViewportHeight;
if (viewportHeight + verticalOffset == extentHeight)
{
BackButton.Visibility = Visibility.Collapsed;
}
else
{
BackButton.Visibility = Visibility.Visible;
}
}
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
var verticalOffset = scrollViewer.VerticalOffset;
var extentHeight = scrollViewer.ExtentHeight;
var viewportHeight = scrollViewer.ViewportHeight;
if (viewportHeight + verticalOffset == extentHeight)
{
BackButton.Visibility = Visibility.Collapsed;
}
else
{
BackButton.Visibility = Visibility.Visible;
}
}
If you have any other concerns, please feel free to contact me.