question

mcosmin222-2039 avatar image
0 Votes"
mcosmin222-2039 asked ·

Preventing listview from scrolling back to the top when removing item

I have this listview which displays a large number of items. The UI also allows me to remove any item from the listview. I scroll around the middle of the listview, and I remove an item. When that happens, the listview scrolls back to the top. I want to prevent that. I tried using however,

ItemsStackPanel ItemsUpdatingScrollMode="KeepScrollOffset"

this does not seem to work. The scroll is back to top when I remove the item. I replaced the ItemStackPanel with a VirtualizingStackPanel and everything works as expected, except I learned that VirtualizingStackPanel is somehow lower performance than ItemStackPanel. So how do I get to use the "KeepScrollOffset" properly?

windows-uwpwindows-uwp-xaml
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

NicoZhu-MSFT avatar image
0 Votes"
NicoZhu-MSFT answered ·

Preventing listview from scrolling back to the top when removing item

Please use ObservableCollection type to replace List type for ItemsSource. And avoid re-set the ItemsSource after removing the item. Please check the following demo code.

 public MainPage()
 {
     this.InitializeComponent();
     this.Loaded += MainPage_Loaded;
      
 }
 private ObservableCollection _items;
 private void MainPage_Loaded(object sender, RoutedEventArgs e)
 {
      _items = new ObservableCollection();
     for (int i = 0; i < 100; i++)
     {
         _items.Add($"Cuttent index is {i}");
     }
     MyListView.ItemsSource = _items;
 }
    
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     _items.RemoveAt(60);
 }


· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.