当我试图实现无限滚动页时,我遇到了CurrentItemChanged事件Xamarin.Forms.CarouselView的奇怪行为。
当用户滚动时,新项将添加到ItemSource中,旧项将被删除(以降低内存消耗)。
当我遇到这种奇怪的行为后,我调整了一下,缩小了问题范围。
以下是复制这种情况的步骤。
CarouselView.
ObservableCollection<T>,并将其分配给ItemSource.
CarouselView的CurrentItemChanged事件。此方法必须在某个时候从CurrentItem.
ItemSource中删除一个元素,该元素在0和0的索引之间有一个索引,部署应用程序并滑动CarouselView一次。这将导致一个没完没了的滚动循环,直到所有项目都从ItemSource.中移除为止。
步骤3中的方法必须如下所示。
bool FirstTime = true;
private void StateChanged(object s, EventArgs e)
{
// Pass the first call which is made right after the Carousel is initialized.
if (FirstTime) { FirstTime = false; return; }
var currentItem = (Model)Carousel.CurrentItem; // For debug.
var index = Models.IndexOf(currentItem); // Same.
// Step 3's requirement
Models.RemoveAt(0);
}例如,当您向页面添加一个按钮并将步骤3中创建的方法分配给它的Clicked事件时,继续执行第4步,然后在每次滚动之后手动按下按钮,就不会出现无穷无尽的循环。
我不知道这是一个特性还是一个bug,但这肯定是出乎意料的,至少对我来说是这样。我想找出如何克服这个问题,并了解为什么它是这样工作的。
注意:我知道删除当前项会导致这样的问题,但无论哪种方式都会发生所描述的行为。此外,在触发CarouselView.CurrentItem事件之前会更新CurrentItemChanged。
发布于 2020-12-02 13:19:51
--这将导致一个没完没了的滚动循环,直到所有项目都从ItemSource中移除为止。
这是因为CollectionChanged事件将在数据收集更改时调用ObservableCollection。删除第一项时,索引将被引用,该事件也将被触发。
对于此函数,您可以检测当前项是否是更新数据收集的最后一个项。检查代码:
public partial class Page1 : ContentPage
{
CustomViewModel viewModel = new CustomViewModel();
ObservableCollection<CustomModel> collection;
public Page1()
{
InitializeComponent();
BindingContext = viewModel;
collection = viewmodel.DataCollection;
}
private void CarouselView_CurrentItemChanged(object sender, CurrentItemChangedEventArgs e)
{
var item = e.CurrentItem as CustomModel;
var index = collection.IndexOf(item);
if (collection.Count == (index + 1))
{
collection.RemoveAt(0);
collection.Add(new CustomModel { ... });
}
}
}https://stackoverflow.com/questions/65106771
复制相似问题