简体   繁体   中英

Xamarin Tabbed Pages MVVM Passing Data Between Pages

I have a TabbedPage called 'TabContainerPage' that is a container for two ContentPage.

<TabbedPage.Children>
        <me:TabbedPage1View Title="Tabbed Page 1" BindingContext="{Binding tabbedPage1ViewModel}" WidthRequest="400"/>
        <me:TabbedPage2View Title="Tabbed Page 2"/>
</TabbedPage.Children> 

In the TabContaierPageViewModel I have a property to the the TabbedPage1ViewModel called 'tabbedPage1ViewModel'

public TabbedPage1ViewModel tabbedPage1ViewModel  { get; set; }

public TabContainerPageViewModel()
{
      tabbedPage1ViewModel = new TabbedPage1ViewModel ();
}

In the TabPage1ViewModel I have a List of Items

private List<Items> _items;

public List<Items> items
{
            get
            {
                return _items;
            }
            set
            {
                _items = value;
                OnPropertyChanged();
            }
}

From the TabPage1View I navigate to another page called 'AddItemView.'

As the name implies, I add a new Item with a simple Name and Description on the AddItemView page.

When I click the back button to go back to TabPage1View I want to update the list of items to be displayed on that page.

How can I accomplish this?

First of all, change List to ObservableCollection.

ObservableCollection implements by itself the OnPropertyChanged, what means that the interface will update when the collection updates.

But you still need to reload your model on TabPage1View (after adding the item and comming back from AddItemView).

You have two options:

First and best, implement a MessagingCenter. Fire a message befor close AddItemView, intercept the message in TabPage1View, update the Observable and your screen will update as well.

Second, do the same at TabPage1View.PageAppearing.

One last hint: sometimes you need to remove one by one the items in the collections, and the add the new items to fire the UI refresh.

If you replace the old observabel witha new one, the UI may not refresh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM