In most scenarios on Windows Phone 8 it's better to use the LongListSelector
instead of the ListBox
control.
Instead of loading all the items at once, the LongListSelector virtualizes its content, only loading data as needed to show in its viewport.
The ItemRealized event fires when a new item is assigned a UI container (realized). Use this event to determine if you are close to the end of the items in the datasource, then load more data.
XAML
<phone:LongListSelector x:Name='longListFlights'
ItemsSource='{Binding}'
ItemRealized='longListFlights_ItemRealized'
Height='205'
Margin='20'>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation='Horizontal'>
<TextBlock Text='{Binding FlightNumber}'
Foreground='Yellow' />
<TextBlock Text='{Binding TimeStamp}'
Margin='20,0,0,0' />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
CODE
public partial class MainPage : PhoneApplicationPage {
private ObservableCollection<Flight> _flights =
new ObservableCollection<Flight>();
private bool _isLoadingData;
public MainPage() {
InitializeComponent();
AddFlights(60);
this.DataContext = _flights;
}
private void AddFlights(int numberFlightsToAdd) {
_isLoadingData = true;
int max = _flights.Count + numberFlightsToAdd;
for (int i = _flights.Count; i < max; i++)
{
_flights.Add(new Flight { FlightNumber = string.Format("AB-{0:D3}", i),
TimeStamp = DateTime.Now });
}
_isLoadingData = false;
}
private void longListFlights_ItemRealized(object sender,
ItemRealizationEventArgs e) {
Flight flight = e.Container.Content as Flight;
if (flight != null)
{
if (!_isLoadingData)
{
// get current count of data-source
int count = _flights.Count;
// get index of item being realized (placed in container)
int index = _flights.IndexOf(flight);
// if we are close to the end, load more data
if (count - index <= 5)
{
AddFlights(10);
}
}
Console.WriteLine(flight.FlightNumber);
}
}
}
internal class Flight {
public string FlightNumber { get; set; }
public DateTime TimeStamp { get; set; }
}
}
Screenshot