CollectionView has the built-in ability to fetch additional data when the user scrolls through the content already loaded. As the data threshold is met, like when only 4 items remain to be displayed, the CollectionView can execute a command to fetch more data and append.
<CollectionView | |
x:Name="cv" | |
ItemsSource="{Binding FlightsToDisplay}" | |
RemainingItemsThreshold="4" | |
RemainingItemsThresholdReachedCommand="{Binding LoadMoreFlightsCommand}" | |
VerticalScrollBarVisibility="Always" | |
Margin="0"> | |
<CollectionView.ItemsLayout> | |
<LinearItemsLayout | |
ItemSpacing="00" | |
Orientation="Vertical"/> | |
</CollectionView.ItemsLayout> | |
<CollectionView.ItemTemplate> | |
<DataTemplate> | |
<views:ResultViewA/> | |
</DataTemplate> | |
</CollectionView.ItemTemplate> | |
</CollectionView> |
public class FlightResultsViewModel : BaseViewModel | |
{ | |
public Command LoadMoreFlightsCommand { get; set; } | |
public FlightResultsViewModel() | |
{ | |
LoadMoreFlightsCommand = new Command(LoadMoreAsync); | |
InitData(); | |
} | |
private async void LoadMoreAsync() | |
{ | |
if (IsBusy) | |
return; | |
IsBusy = true; | |
await Task.Delay(1000); // Fake and API call delay | |
FlightsToDisplay.AddRange( | |
Flights.Skip(batchSize * currentFlightIndex).Take(batchSize) | |
); | |
currentFlightIndex += batchSize; | |
IsBusy = false; | |
} | |
public List<Flight> Flights { get; set; } | |
public List<Flight> FlightsEmpty { get; set; } = new List<Flight>(); | |
public ObservableRangeCollection<Flight> FlightsToDisplay { get => flightsToDisplay; | |
set => SetProperty(ref flightsToDisplay, value); } | |
Random random = new Random(); | |
private void InitData() | |
{ | |
Flights = new List<Flight>(); | |
for (var i = 1; i <= 1000; i++) | |
{ | |
Flights.Add(new Flight | |
{ | |
From = cities[random.Next(cities.Length - 1)], | |
To = cities[random.Next(cities.Length - 1)], | |
DepartDateTime = departDates[random.Next(departDates.Length - 1)], | |
ArrivalDateTime = arrivalDates[random.Next(arrivalDates.Length - 1)], | |
Price = prices[random.Next(prices.Length - 1)] | |
}); | |
} | |
FlightsToDisplay = new ObservableRangeCollection<Flight>(Flights.Take(batchSize).ToList()); | |
} | |
} |
Check it out:
Resources:
Top comments (0)