2

I have a problem where I'm trying to display data inside a ListView in my app when binding a list of data to my ListView in XAML. The ListView does not populate with any data at all.

Here is all my coding:

My Code-behind

public ObservableCollection<RandomList> randomList = new ObservableCollection<RandomList>();

public App()
{
    MainPage = new MainUI();

    randomList.Add(new RandomList { Name = "Susan", Surname = "Potgieter", School = "Oosterlig" });
    randomList.Add(new RandomList { Name = "Jonathan", Surname = "Visagie", School = "Elspark" });
    randomList.Add(new RandomList { Name = "Gerhard", Surname = "Vermaak", School = "E.G. Jansen" });
    randomList.Add(new RandomList { Name = "Kobus", Surname = "Jacobs", School = "Oosterlig" });          
}

My 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"
             x:Class="RandomTest.MainUI">
  <StackLayout Padding="0,40,0,0">
    <Label Text="Hello" VerticalOptions="Center" HorizontalOptions="Center" />
    <Button x:Name="btnGetStudents" Text="Get Students"/>
    <ListView x:Name="lwStudents" ItemsSource="{Binding randomList}">
      <ListView.ItemTemplate>
        <DataTemplate>
          <TextCell Text="{Binding Name}" Detail="{Binding Surname}"/>
        </DataTemplate>
      </ListView.ItemTemplate> 
    </ListView>
  </StackLayout>
</ContentPage>

When I insert a breakpoint in my code behind where I add the dummy data to the list, I can then see in my XAML here: <ListView x:Name="lwStudents" ItemsSource="{Binding randomList}"> that there are 4 items in my randomList.

The problem is that there is no data in the two bindings below:

<TextCell Text="{Binding Name}" Detail="{Binding Surname}"/>

Can someone please tell or show me what I'm doing wrong in my binding? Or if you need ANY more info or code, please ask! I will be happy to give more info. :)

EDIT

I've updated my RandomList class and implemented INotifyPropertyChanged, but I still can't get my data to load in my ListView through XAML bindings.

using System.ComponentModel;

namespace RandomTest
{
    public class RandomList : INotifyPropertyChanged
    {
        public int Id { get; set; }

        string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name != value)
                    _name = value;
                OnPropertyChanged("Name");
            }
        }

        string _surname;
        public string Surname
        {
            get { return _surname; }
            set
            {
                if (_surname != value)
                    _surname = value;
                OnPropertyChanged("Surname");
            }
        }

        string _school;
        public string School
        {
            get { return _school; }
            set
            {
                if (_school != value)
                    _school = value;
                OnPropertyChanged("School");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

EDIT 2

This is how my MainUI.xaml.cs page looks like at the moment:

public partial class MainUI : ContentPage
{
    public MainUI()
    {
        InitializeComponent();
        BindingContext = new MainUIModel();

        MainUIModel mainUIModel = (MainUIModel)this.BindingContext;
        mainUIModel.randomList.Add(new RandomList { Name = "Susan", Surname = "Potgieter", School = "Oosterlig" });
        mainUIModel.randomList.Add(new RandomList { Name = "Jonathan", Surname = "Visagie", School = "Elspark" });
        mainUIModel.randomList.Add(new RandomList { Name = "Gerhard", Surname = "Vermaak", School = "E.G. Jansen" });
        mainUIModel.randomList.Add(new RandomList { Name = "Kobus", Surname = "Jacobs", School = "Oosterlig" });
    }
}
7
  • Do you have INotifyPropertyChanged inherited in your model which you might have set as BindingContext? Commented Jun 8, 2016 at 8:54
  • Hello! :) No I have no INotifyPropertyChanged for the class. Do you think it could help? It's strange because I can set the itemsource of the listview in code and it displays all the data, but it doesn't work in XAML... :| Commented Jun 8, 2016 at 9:58
  • Yes that's required in your model.@CareTaker22 developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/… Commented Jun 8, 2016 at 9:59
  • I will go and test INotifyPropertyChanged in the class and let you know if it works. Thanks! Commented Jun 8, 2016 at 10:01
  • I've update my class and my question with the class that i've implemented INotifyPropertyChanged and it still doesn't return any data. Could the binding in XAML be wrong? Commented Jun 8, 2016 at 10:16

2 Answers 2

3

Create a model MainUIModel

public class MainUIModel : INotifyPropertyChanged
{
    ObservableCollection<RandomList> _randomList;
    public ObservableCollection<RandomList> randomList
    {
        get { return _randomList; }
        set
        {
            if (_randomList != value)
                _randomList = value;
            OnPropertyChanged("randomList");
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

And then in your MainUI Page set the binding context just after initialize component.

BindingContext = new MainUIModel();

The binding randomList in your Xaml will refer to this new created model, and your Name, Surname will refer to the list model. Both binding context are different. You can add your data by using the below code.

MainUIModel mainUIModel = (MainUIModel)this.BindingContext;
mainUIModel.randomList=new ObservableCollection<RandomList>();
    mainUIModel.randomList.Add(new RandomList { Name = "Susan", Surname = "Potgieter", School = "Oosterlig" });
    mainUIModel.randomList.Add(new RandomList { Name = "Jonathan", Surname = "Visagie", School = "Elspark" });
    mainUIModel.randomList.Add(new RandomList { Name = "Gerhard", Surname = "Vermaak", School = "E.G. Jansen" });
    mainUIModel.randomList.Add(new RandomList { Name = "Kobus", Surname = "Jacobs", School = "Oosterlig" });  
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks for the answer Akash. I've done like you've suggested but i'm getting the error System.NullReferenceException: Object reference not set to an instance of an object at the line: MainUIModel mainUIModel = (MainUIModel)this.BindingContext;.
Where have you put this line? It must be in your MainUI page becuase the bindingcontext will set on the MainUI page and this also refers to your MainUI page.
In my public class App : Application window, where I add the dummy-data to the list.
No it will not work, this will refer to your App class.
I've added the line to the MainUI page, but it's still giving me the same error. I've also added the list coding where I add data to my randomList to the MainUI page. I don't really know if I'm doing something wrong here 0_o, but i've updated my question so you might have a better idea of what i'm doing wrong. Sorry for all the inconvenience!
|
3

Really all you needed to do was make sure the ObservableCollection had a public getter. Then you could just set BindingContext = this and you could access this on the UI. But as always, there are many many ways to skin these kittens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.