[FIXED] Xamarin.Forms ListView Binding Issue

Issue

We are a newbie for Xamarin. We are having an issue in binding the response data from a web service to a ListView.

We debugged and we can see the the web service is successfully responding with the data but it never gets populated.

Any ideas?

It’s gotta be a small thing that we are missing. We have managed to display a single entry from the data with other views (in other parts of the project) BUT not in IEnumerable<> or List<>

Here’s the code:

View – RoundsPage.xaml :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:AthlosifyMobile.ViewModels"
             x:Class="AthlosifyMobile.Views.RoundsPage">

    <ContentPage.BindingContext>
        <viewModels:RoundsViewModel />
    </ContentPage.BindingContext>

    <StackLayout>

        <Entry Text="{Binding AccessToken}" />
        <Button Command="{Binding GetRoundsCommand}" Text="Get all rounds" />
        <Label Text="Rounds: "></Label>
        <ListView ItemsSource="{Binding Rounds}" HasUnevenRows="true"  >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Round 1:"></Label>
                            <Label Text="{Binding Name}"></Label>
                            <Label Text="{Binding DailyHandicap}"></Label>
                            <Label Text="{Binding PlayedUTC}"></Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>`

ViewModel – RoundsViewModel.cs :

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Input;
using AthlosifyMobile.Annotations;
using Xamarin.Forms;
using AthlosifyMobile.Services;
using AthlosifyMobile.Models;

namespace AthlosifyMobile.ViewModels
{ 
    public class RoundsViewModel : INotifyPropertyChanged
    {
        ApiServices _apiServices = new ApiServices();
        public event PropertyChangedEventHandler PropertyChanged;
        private IEnumerable<Round> _rounds;
        public string AccessToken { get; set; }
        public IEnumerable<Round> Rounds
        {
            get
            {
                return _rounds;
            }
            set
            {
                _rounds = value;
                OnPropertyChanged();
            }
        }

        public ICommand GetRoundsCommand
        {
            get
            {
                return new Command(async() =>
                {
                    Rounds = await _apiServices.GetRoundsAsync(AccessToken);
                });
            }
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Model – Course.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace AthlosifyMobile.Models
{
    public class Round : EntityBase
    {
        public Guid RoundID { get; set; }
        public Guid UserID  { get; set; }
        public Guid RoundCategoryID { get; set; }
        public Guid CourseID { get; set; }
        public string Name { get; set; }
        public string Notes { get; set; }
        public int DailyHandicap { get; set; }
        public DateTime PlayedUTC { get; set; }
        public RoundCategory RoundCategory { get; set; }
        public Course Course { get; set; }

        public ICollection<RoundHole> RoundHoles { get; set; }
    }   

    public abstract class EntityBase
        {
            public DateTime CreatedUTC { get; set; }

            public DateTime LastModifiedUTC { get; set; }
        }
}

Services – apiservices.cs:

using AthlosifyMobile.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace AthlosifyMobile.Services
{

        public async Task<IEnumerable<Round>> GetRoundsAsync(string accessToken)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var json = await client.GetStringAsync("http://localhost:5609/api/Rounds");
            var list = JsonConvert.DeserializeObject<IEnumerable<Round>>(json);

            return list;
        }
    }
}

Solution

You will need to diagnose whether this is an issue with connecting the View to the ViewModel or whether your Data Service isn’t working correctly. Either way, there are a few things you should do to fix this!

Firstly you are using IEnumerable, instead you should be using ObservableCollection<T>. You should always be using ObservableCollection<T> for Binded list views. This is explained in the xamarin docs here (they automatically notify the view when their contents changed & update).

So you should make this change:

public ObservableCollection<Round> Rounds { get; }

Next you should verify that the bindings are correct. I would not recommend your approach of going straight to live data if you aren’t familiar with xamarin. Firstly you should try adding some static objects to the view model and trying to bind them!

Disconnect your API code and call a method that creates some of your Round objects. Here is an example method (i use methods like these all the time when designing my ListViews UI).

public RoundsViewModel()
{
    Rounds = CreateSampleData();
}

private ObservableCollection<Round> CreateSampleData()
{
    ObservableCollection<Round> dummyData = new ObservableCollection<Round>();

    dummyData.Add(new Round() { Name="User", handicap=1, PlayedUTC=DateTime.Now });
    dummyData.Add(new Round() { Name="User", handicap=1, PlayedUTC=DateTime.Now });
    dummyData.Add(new Round() { Name="User", handicap=1, PlayedUTC=DateTime.Now });

    return dummyData;
}

At this point you will either see items in your ListView, meaning you have an issue with your API code / Implementation of INotifyPropertyChanged. If you don’t see anything then you likely have an issue with binding and will need to verify that your view is actually connected to the View Model.

Mvvm Helpers

Seeing some of this code makes me feel very sorry for you, you definitely should looking into using an MVVM helper such as Prism or MVVMCross. I personally use Prism which provides a ViewModelBase which all ViewModels inherit from. This means all of the INotifyPropertyChanged code is hidden away from you (less boilerplate). It also has a dependancy service which means hooking views up to view models is as simple as registering it in the app.cs.

If you are interested in prism, watch this video with Brian Lagunas to see what Prism can do for you!

Update: There are now a few helpful libraries aside from Prism that will help with the MVVM stuff. Refractored.MVVMHelpers and Xamarin.CommunityToolkit both contain an essential object: ObservableRangeCollection.

ALL code using an ObservableCollection should be replaced with ObservableRangeCollection, it is an essential object and really belongs in a microsoft maintained namespace at this point. It creates a performance benefit for updating larger collections & reduces the need for alot of boilerplate when updating the ObservableCollection

Answered By – Axemasta

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published