Quiero hacer un listview paginado y para hacerlo quiero que al hacer el scroll carguen más resultados. Para ello se me ha ocurrido hacer un método que me carga unos reultados y que al hacer el scroll me agregue más datos pero cuando se agregan más datos entra en un bucle infinito. Este es el código del viewmodel que uso :
public class MainViewModel:INotifyPropertyChanged
{
private ObservableCollection<data> items;
public ListView Lista { get; set; }
public ObservableCollection<data> Items { get => items; set
{ items = value;NotifyPropertyChanged(nameof(Items)); } }
public MainViewModel(ListView l)
{
Lista = l;
Lista.Scrolled += Lista_Scrolled;
Items = new ObservableCollection<data>();
datos();
}
public event PropertyChangedEventHandler PropertyChanged;
private async void Lista_Scrolled(object sender, ScrolledEventArgs e)
{
await agregar();
}
private async Task datos()
{
await Task.Run(() => {
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "ar", dr = "df" });
Items.Add(new App51.data { ar = "xx", dr = "df" });
Items.Add(new App51.data { ar = "xx", dr = "df" });
Items.Add(new App51.data { ar = "ff", dr = "df" });
});
Lista.ItemsSource = Items;
}
private async Task agregar()
{
ObservableCollection<data> aux = Items;
Items.Clear();
await Task.Run(()=> {
aux.Add(new App51.data { ar = "ff", dr = "df" });
aux.Add(new App51.data { ar = "rr", dr = "df" });
aux.Add(new App51.data { ar = "rr", dr = "df" });
aux.Add(new App51.data { ar = "rr", dr = "df" });
aux.Add(new App51.data { ar = "ff", dr = "df" });
aux.Add(new App51.data { ar = "ff", dr = "df" });
aux.Add(new App51.data { ar = "ff", dr = "df" });
aux.Add(new App51.data { ar = "hh", dr = "df" });
aux.Add(new App51.data { ar = "hh", dr = "df" });
aux.Add(new App51.data { ar = "hh", dr = "df" });
});
Items = aux;
Lista.ItemsSource = Items;
}
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}