GordonR
GordonR

Reputation: 1

CollectionView not updating

I have a CollectionView set up in the View as:

<CollectionView ItemsSource="{Binding Staffmembers}">
   <CollectionView.ItemTemplate>
                 <DataTemplate >
                     ...
                 </DataTemplate>
   </CollectionView.ItemTemplate>
</CollectionView>

The ViewModel defines the Staffmembers ItemsSource as an observable collection:

        public StaffViewModel()
        {
            Staffmembers = new ObservableCollection<Staff>(App.StaffRepo.GetStaff());

        }
        [ObservableProperty]
        ObservableCollection<Staff> staffmembers;

When I add a new item to this collection it is supposed to update

        public void AddStaff()
        {
            Staffmember.Name= name;
            Staffmember.Surname= surname;
            Staffmember.Role= role;


            try
            {
                App.StaffRepo.SaveStaff(Staffmember);
                Staffmembers = new ObservableCollection<Staff>(App.StaffRepo.GetStaff());
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            Shell.Current.GoToAsync("//Staff");
        }

The problem is that when I add to the collection, the change isn't reflected in the CollectionView. If I reload the collection, the change shows up, but I want it to reflect immediately. I've seen this done in tutorials but I'm just not sure what I'm missing

Upvotes: 0

Views: 374

Answers (2)

Guangyu Bai - MSFT
Guangyu Bai - MSFT

Reputation: 4486

This code below might cause the ObservableCollection not work.

App.StaffRepo.SaveStaff(Staffmember);
Staffmembers = new ObservableCollection<Staff>(App.StaffRepo.GetStaff());

You should add the data to the ObservableCollection directly. Such as

Staffmembers = new ObservableCollection<Staff>();
Staffmembers.Add(new Staff { Name = "1" });

Upvotes: 0

Gerald Versluis
Gerald Versluis

Reputation: 33993

The problem is that you do this in the AddStaff method: Staffmembers = new ObservableCollection<Staff>(App.StaffRepo.GetStaff());.

Once you created a new ObservableCollection you should clear it and repopulate it (or just add a single record, however you want to add new things). If you create a new instance it will lose the data binding connection and will stop updating the UI.

So change it into something like this:

public void AddStaff()
{
    Staffmember.Name= name;
    Staffmember.Surname= surname;
    Staffmember.Role= role;


    try
    {
        App.StaffRepo.SaveStaff(Staffmember);
        Staffmembers.Clear();

        foreach(var member in App.StaffRepo.GetStaff())
            Staffmembers.Add(member);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }

    Shell.Current.GoToAsync("//Staff");
}

Upvotes: 1

Related Questions