Home > Software design >  WPF goes to the top of each pages when navigating/reloading page
WPF goes to the top of each pages when navigating/reloading page

Time:05-04

I'm very new to WPF .net 5.0 framework. I am currently developing a system with it. Every time I navigate to a different page in a frame, it maintains the scroll position instead of going back to the top of the page. May I know if there is a way to make sure that it goes to the top of the page every time I navigate? Thank you!

this is the xaml

<ScrollViewer Height="1000" Width="1000" HorizontalScrollBarVisibility="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="23*"/>
                <RowDefinition Height="477*"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0">
                <TextBlock HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Center" FontWeight="Bold" Foreground="#FF5B5858"><Run Language="en-sg" Text="ADD NEW APPLICATION"/></TextBlock>

            </Grid>
            <Grid Grid.Row="1" Margin="0,10,0,0">
                <Border CornerRadius="0,0,30,0" BorderThickness="1">
                    <Frame x:Name="wizardFrame" Content="Frame" HorizontalAlignment="Center" Width="1002" Margin="0,9,0,471" NavigationUIVisibility="Hidden"/>
                </Border>
            </Grid>
        </Grid>
    </ScrollViewer>

This is the code behind

wizardFrame.NavigationService.Navigate(new LocationPage1());

This is what i use to navigate to different pages in a frame

this.NavigationService.Navigate(new GenerateApplicationNumberPage2());

CodePudding user response:

Your issue is that the ScrollViewer has no relation to the Frame, so it won't react to the Frame navigating.
In order to fix that, I see two solutions (pick one):

  1. You name your ScrollViewer (e.g: mainScroll), and in the code-behind, you subscribe to the Navigated event of your Frame, so as to call ScrollViewer.ScrollToTop(), as suggested in a comment.
// Somewhere in the constructor after InitializeComponent();
wizardFrame.Navigated  = (_, __) => mainScroll.ScrollToTop();
  1. You remove the ScrollViewer from your main page, and add one as the root element in the XAML of each Page (LocationPage1, GenerateApplicationNumberPage2, and any other page). It will work because you create a new page each time you navigate (which isn't very good for resource management, but this is not the subject here).
    The difference will be that the TextBlock with "ADD NEW APPLICATION" will always be visible above the Pages instead of being inside the ScrollViewer.
<Page x:Class="Namespace.LocationPage1">
  <ScrollViewer Height="1000" Width="1000">
    <!-- Your page content here -->
  </ScrollViewer>
</Page>
  • Related