Adding pull-to-refresh

As with the new entry page, when the main page is loading our data, we should present the user with a loading indicator so that they know their list of entries is on its way. However, since the main page is using a data-bound ListView instead of a static TableView, we can use the ListView pull-to-refresh functionality to indicate when our data is being loaded. Pull-to-refresh also has the benefit of allowing users to easily refresh the screen and load any new data that might be available. Xamarin.Forms makes adding pull-to-refresh very easy, and we will still use the IsBusy property from our BaseViewModel, just as we did on the new entry page. 

The Xamarin.Forms ListView pull-to-refresh API requires two things: an ICommand that handles refreshing the bound source of the ListView, and a boolean field that indicates whether the ListView is currently refreshing or not. To add pull-to-refresh, perform the following steps:

  1. First, we will need to add a new refresh command to MainViewModel. This command will simply call the existing LoadEntries() method:
      Command _refreshCommand;
public Command RefreshCommand
{
get
{
return _refreshCommand
?? (_refreshCommand = new Command(
async () => await LoadEntries()));
}
}
  1. Next, we will need to update the LoadEntries method to set IsBusy while it's loading its data. For now, just as we did earlier in the chapter with the NewEntryViewModel, we will add a three-second delay to simulate a waiting period (we will remove this in the next chapter when we start getting our data from a live web service):
      async Task LoadEntries()
{
if (IsBusy)
{
return;
}

IsBusy = true;

LogEntries.Clear();

// TODO: Remove this in chapter 6
await Task.Delay(3000);

LogEntries.Add(new TripLogEntry
{
// ...
});

LogEntries.Add(new TripLogEntry
{
// ...
});

LogEntries.Add(new TripLogEntry
{
// ...
});

IsBusy = false;
}
  1. Next, we will need to update the ListView tag in MainPage.xaml to enable pull-to-refresh and to bind its RefreshCommand property to the new RefreshCommand command we just added in MainViewModel. For the ListView IsRefreshing property, we can simply bind to IsBusy, as that will be set to true while we're loading entries and back to false when that operation is complete:
      <ListView ... ItemsSource="{Binding LogEntries"
IsPullToRefreshEnabled="True"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
RefreshCommand="{Binding RefreshCommand}">

Now when we run the app, we will see the pull-to-refresh spinner while the data initially loads on the main page, as well as when the user pulls down on the list, as shown in the following screenshot: 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.79.63