当我更新绑定到我的ObservableCollection的ListView时,它会自动滚动到顶部。
我当前获取数据的代码如下所示,记录是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>
是否有任何方法禁用此行为,因为它确实导致了一个非常糟糕的UX。我试过逐个更新每一件物品,但没能做到。谢谢。
发布于 2021-07-01 06:44:42
我可以复制你的问题。原因是在添加项之前使用Books.Clear()
清除数据源,这会导致ItemsSource of ListView为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; }
}
https://stackoverflow.com/questions/68190622
复制相似问题