C# – Xamarin.Forms – ListView does not update when data changes

cxamarinxamarin.forms

Problem: Data changes but ListView does not update

I have a ListView whose ItemsSource is set to

<ListView ItemsSource="{Binding ContactsGrouped}" 

On click of a button I update the query to only return records that contain the letters "Je". I can see that the right thing is being returned, and that ContactsGrouped is being updated, but the UI does not change.

public ObservableCollection<Grouping<string, Contact>> ContactsGrouped { get; set; }

where Grouping looks like this:

public class Grouping<K, T> : ObservableCollection<T>
{
    public K Key { get; private set; }

    public Grouping ( K key, IEnumerable<T> items )
    {
        Key = key;
        foreach ( var item in items )
            this.Items.Add( item );
    }
}

Given that I'm using ObservableCollections, I'd expect the list to redraw. Am I missing something obvious?

Best Answer

I presume the Grouping class is utilised from a ViewModel. In which case that ViewModel has to implement the INotifyPropertyChanged interface such as below:

#region INotifyPropertyChanged implementation

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged ([CallerMemberName]string propertyName = null)
{
    if (PropertyChanged != null) {
        PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
    }
}

#endregion

As long as you call the OnPropertyChnaged method on setting the property then you will get the results of the binding.

Related Topic