Search code examples
c#jsonmvvmwindows-store-apps

Listview will not update everytime when i'm loading JSON file


I'm making a Windows store app using the MVVM pattern. When i'm loading my dictionary from a JSON file and binding it to the listview, then it won't update everytime i switch view. Sometimes the listview is updating, sometimes not. Some suggestions for what goes wrong?

class KundePersistency

public static async Task<List<Kunde>> LoadKunderFromJsonAsync()
{
    string kundeJsonString = await DeserializekunderFileAsync(JsonFileKunder);
    if (kundeJsonString != null)
        return (List<Kunde>)JsonConvert.DeserializeObject(kundeJsonString, typeof(List<Kunde>));
    return null;
}

private static async Task<string> DeserializekunderFileAsync(string fileName)
{
    try
    {
        StorageFile localFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
        return await FileIO.ReadTextAsync(localFile);
    }
    catch (FileNotFoundException)
    {
        return null;
    }
}

Class BookingSystem (ViewModel)

private async void LoadKunder()
{
    _id = 1;
    var loadedKunder = await KundePersistency.LoadKunderFromJsonAsync();

    if (loadedKunder != null)
    {
        KundeRegister.KundeMedId.Clear();
        foreach (var kunde in loadedKunder)
        {
            KundeRegister.KundeMedId.Add(_id++, kunde);

        }
    }
}

Class KundeRegister (Model)

public class KundeRegister : INotifyPropertyChanged
{
   public Dictionary<int, Kunde> KundeMedId { get; set; }


public KundeRegister()
{
    KundeMedId = new Dictionary<int, Kunde>();           
    KundeMedId.Add(Kunde.Id,new Kunde("bob","bob","bob","bobbobbo","bob","bob"));
    KundeMedId.Add(Kunde.Id, new Kunde("bob", "bob", "bob", "bobbobbo", "bob", "bob"));

}

public void AddKunde(string username, string password,string adresse,string email, string name, string tlf)
{
    KundeMedId.Add(Kunde.Id, new Kunde(adresse, email, name, tlf, username, password));
    OnPropertyChanged();
}


public event PropertyChangedEventHandler PropertyChanged;

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

}

Solution

  • You need to User ObeservableCollection for your as Dictionary does not Implement INotifyPropertyChanged By Default

     private ObservableCollection<NavigationItem> _loadedKunder ;
        public ObservableCollection<NavigationItem> loadedKunder
        {
            get { return _loadedKunder ; }
            set
            {
                if (value != _loadedKunder )
                {
                    _loadedKunder = value;
                    NotifyPropertyChanged("loadedKunder");
                }
            }
        }