Preventing listview from scrolling back to the top when removing item

mcosmin222 1 Reputation point
2020-01-28T17:16:30.033+00:00

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?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,851 Reputation points
    2020-01-29T07:27:26.83+00:00

    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);  
    }  
    
    0 comments No comments