2014-11-25 17 views
7

Problema: le modifiche dei dati, ma ListView non aggiornaXamarin.Forms - ListView non si aggiorna quando i dati cambia

Ho un ListView cui ItemsSource è impostato su

<ListView ItemsSource="{Binding ContactsGrouped}" 

Su clic di un pulsante Aggiorno la query per restituire solo i record che contengono le lettere "Je". Posso vedere che viene restituita la cosa giusta e che ContactsGrouped è in fase di aggiornamento, ma l'interfaccia utente non cambia.

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

dove raggruppamento si presenta così:

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); 
    } 
} 

Premesso che sto usando ObservableCollections, mi aspetto la lista per ridisegnare. Mi manca qualcosa di ovvio?

risposta

1

Si scopre che l'implementazione di INotifyPropertyChanged non aggiornerà l'elenco durante il filtraggio. Tuttavia, prendere in considerazione il codice che compila l'elenco nella VM e quindi chiamare quel codice nel metodo OnTextChanged (seguito da una chiamata alla reimpostazione di ItemsSource) fa il trucco.

public void OnTextChanged (object sender, TextChangedEventArgs e) { 
     vm.PopulateContacts(vm.CurrentDataService); 
     ContactListView.ItemsSource = vm.ContactsGrouped; 
    } 

I PopulateContacts metodo simile a questo (abbreviata) ...

// setup 
    // Get the data 
     var sorted = 
      from contact in contacts 
      orderby contact.FullName 
      group contact by contact.FirstInitial 
      into contactGroup 
      select new Grouping<string, Contact> (contactGroup.Key, contactGroup); 

     contactsGrouped = new ObservableCollection<Grouping<string, Contact>> (sorted); 

che funziona, ed è ragionevolmente pulito e verificabile

1

Suppongo che la classe di raggruppamento sia utilizzata da un ViewModel. In tal caso che ViewModel deve implementare l'interfaccia INotifyPropertyChanged come di seguito:

#region INotifyPropertyChanged implementation 

public event PropertyChangedEventHandler PropertyChanged; 

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

#endregion 

Finché si chiama il metodo OnPropertyChnaged sull'impostazione della proprietà allora si ottengono i risultati degli attacchi.

Problemi correlati