Search code examples
c#xamarinmvvmcross

MvxObservableCollection does not update the UI


I have a MvxListView, which has a MvxObservableCollection as its ItemsSource:

View.xml

...
            <Mvx.MvxListView
                android:layout_width="fill_parent"
                android:layout_weight="6"
                android:layout_height="wrap_content"
                android:divider="@null"
                local:MvxItemTemplate="@layout/navigationmenuitemrow"
                local:MvxBind="ItemsSource MenuItems; ItemClick NavigateCommand"/>
...

ViewModel.cs

...
private MvxObservableCollection<NavigationItemViewModel> _menuItems = new MvxObservableCollection<NavigationItemViewModel>();

        public MvxObservableCollection<NavigationItemViewModel> MenuItems
        {
            get => _menuItems;
            set
            {
                _menuItems = value;
                RaisePropertyChanged(() => MenuItems);
            }
        }
...

My NavigationItemViewModel looks like this:

    public class NavigationItemViewModel : MvxNotifyPropertyChanged
    {
        public string NavigationCode { get; set; }

        public string DisplayText { get; set; }

        public string Selector { get; set; }

    }

When I initialize the ViewModel with data for the MenuItems, I am able to see all the items in the View. But if I remove all entries from the list and replace them with new entries, the View does not get updated until I touch the screen again. I'm removing the entries like this:

MvxObservableCollection<NavigationItemViewModel> tmpList = new MvxObservableCollection<NavigationItemViewModel>();
foreach (var navigationMenuItem in _navigationMenu.ChildNodes)
{
    tmpList.Add(Map(navigationMenuItem));
}
MenuItems = tmpList;

I've also tried this before:

MenuItems.Clear();
foreach (var navigationMenuItem in _navigationMenu.ChildNodes)
{
    MenuItems.Add(Map(navigationMenuItem));
}

What could be the cause of this? Any help would be much appreciated!


Solution

  • Well, I found the root of my problem:

    I did not set the MvxObservableCollection to a new MvxObservableCollection in the constructor but in the Initialize method instead, which lead to this behaviour. Therefore the binding probably wasn't sustained on changes.