Let ListView scroll to selected item

前端 未结 2 866
南笙
南笙 2021-01-18 07:46

I have a WinRT/C#/XAML app with a view that has a vertical ListView of items. Depending on the amount of items the ListView shows a vertical scrollbar. Here\'s the XAML defi

相关标签:
2条回答
  • 2021-01-18 07:51

    I had a similar need and resolved it in a slightly different manner. I subscribed to the SelectionChangedEvent from the ListView and performed the scrolling within the handler.

    XAML:

    <ListView x:Name="myListView" SelectionChanged="myListView_SelectionChanged" ...>
    </ListView>
    

    Code:

    private void myListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        myListView.ScrollIntoView(myListView.SelectedItem);
    }
    
    0 讨论(0)
  • 2021-01-18 08:15

    Thanks to Filip I noticed that calling ScrollIntoView() in OnNavigatedTo() was too early, because the ListView control is not loaded yet in this place.

    The first solution idea was to bind the Loaded event of the ListView:

    myListView.Loaded += (s, e) => 
        myListView.ScrollIntoView(MyViewModel.SelectedItem);
    

    Unfortunately that causes a nasty visual effect, where current ListView items overlap with the selected item for parts of a second, before everything is rearranged well.

    The final solution I found is to call ScrollIntoView() asynchronously via the Dispatcher of the view:

    myListView.Loaded += (s, e) => Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () => myListView.ScrollIntoView(MyViewModel.SelectedItem));
    

    With this solution the layouting works fine.

    0 讨论(0)
提交回复
热议问题