更新 ObservableCollection 时阻止 UWP ListView 滚动到顶部

Stop UWP ListView from scrolling to top when updating ObservableCollection

当我更新绑定到 ListView 的 ObservableCollection 时,它会自动滚动到顶部。

我获取数据的代码当前看起来像这样,记录是 ObsevableCollection:

        public async Task getData()
        {

            var client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(new Uri("https://api.nomics.com/v1/currencies/ticker?key=<api key>&limit=10"));
            var jsonString = await response.Content.ReadAsStringAsync();
            JsonArray root = JsonValue.Parse(jsonString).GetArray();
            records.Clear();
            for (uint i = 0; i < root.Count; i++)
            {
                string id = root.GetObjectAt(i).GetNamedString("id");
                string name = root.GetObjectAt(i).GetNamedString("name");
                decimal price = decimal.Parse(root.GetObjectAt(i).GetNamedString("price"));
                records.Add(new Coin {
                    id = id,
                    name = name,
                    price = Math.Round(price, 4),
                    logo = "https://cryptoicon-api.vercel.app/api/icon/" + id.ToLower()
                });
            };
           
        }

我的XAML-布局:

 <ListView x:Name="CoinsLV" Grid.Row="1" IsItemClickEnabled="True" ItemClick="listView_ItemClick" ScrollViewer.VerticalScrollMode="Auto">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Padding="5">
                        <Image Width="50" Height="50">
                            <Image.Source>
                                <BitmapImage UriSource="{Binding logo}" />
                            </Image.Source>
                        </Image>
                        <StackPanel>
                        <TextBlock Text="{Binding name}" 
                           Margin="20,0,0,0"
                           FontSize="18" 
                           FontWeight="SemiBold"
                           Foreground="DarkGray" />
                        <TextBlock Text="{Binding price}" 
                           Margin="20,0,0,0"
                           FontSize="20"
                           Foreground="White" 
                           Opacity="1" />
                    </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsStackPanel ItemsUpdatingScrollMode="KeepItemsInView" />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>

有什么方法可以禁用此行为,因为它会导致非常糟糕的用户体验。 我试过单独更新每个项目,但无法正常工作。 谢谢

我可以重现你的问题。原因是你在添加item之前使用Books.Clear()清空数据源,导致ListView的ItemsSource为null,导致listView会滚动到顶部。

为了解决这个问题,您需要创建一个集合来记录以前的项目,然后您可以从总集合中删除这些以前的项目。

如下:

Xaml代码:

<ListView IsItemClickEnabled="True" ScrollViewer.VerticalScrollMode="Auto" ItemsSource="{x:Bind Books}" Height="600">
…
</ListView> 

后面的代码:

public sealed partial class MainPage : Page
    {
        public ObservableCollection<Book> Books;
        public ObservableCollection<Book> OldBooks;
        public MainPage()
        {
            this.InitializeComponent();
            Books =new ObservableCollection<Book>()
            {
                    new Book(){logo=new Uri("ms-appx:///Assets/2.JPG"), name="Chinese",price=25},
                    new Book(){logo=new Uri("ms-appx:///Assets/2.JPG"), name="English",price=26},
                   ……
           };
            OldBooks = new ObservableCollection<Book>();
            foreach (var book in Books)
            {
                OldBooks.Add(book);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e) //update button
        {
          
            Books.Add(new Book() { logo = new Uri("ms-appx:///Assets/1.JPG"), name = "Math", price = 20 });
             ……
            Books.Add(new Book() { logo = new Uri("ms-appx:///Assets/1.JPG"), name = "Chenstry", price = 30 });      

            foreach(var item in OldBooks)
            {
                Books.Remove(item);
            }
        }
    }
    public class Book
    {
        public Uri logo { get; set; }
        public string name { get; set; }
        public int price { get; set; }
    }