简体   繁体   English

Xamarin 标签页 MVVM 在页面之间传递数据

[英]Xamarin Tabbed Pages MVVM Passing Data Between Pages

I have a TabbedPage called 'TabContainerPage' that is a container for two ContentPage.我有一个名为“TabContainerPage”的 TabbedPage,它是两个 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'在 TabContaierPageViewModel 我有一个名为“tabbedPage1ViewModel”的 TabbedPage1ViewModel 属性

public TabbedPage1ViewModel tabbedPage1ViewModel  { get; set; }

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

In the TabPage1ViewModel I have a List of Items在 TabPage1ViewModel 我有一个项目列表

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.'我从 TabPage1View 导航到另一个名为“AddItemView”的页面。

As the name implies, I add a new Item with a simple Name and Description on the AddItemView page.顾名思义,我在 AddItemView 页面上添加了一个带有简单名称和描述的新项目。

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.当我单击后退按钮返回 TabPage1View 时,我想更新要在该页面上显示的项目列表。

How can I accomplish this?我怎样才能做到这一点?

First of all, change List to ObservableCollection.首先,将 List 更改为 ObservableCollection。

ObservableCollection implements by itself the OnPropertyChanged, what means that the interface will update when the collection updates. ObservableCollection 自己实现了 OnPropertyChanged,这意味着当集合更新时接口也会更新。

But you still need to reload your model on TabPage1View (after adding the item and comming back from AddItemView).但是您仍然需要在 TabPage1View 上重新加载您的模型(在添加项目并从 AddItemView 返回之后)。

You have two options:您有两个选择:

First and best, implement a MessagingCenter.首先也是最好的,实现一个 MessagingCenter。 Fire a message befor close AddItemView, intercept the message in TabPage1View, update the Observable and your screen will update as well.在关闭 AddItemView 之前触发一条消息,拦截 TabPage1View 中的消息,更新 Observable,您的屏幕也会更新。

Second, do the same at TabPage1View.PageAppearing.其次,在 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.最后一个提示:有时您需要一个一个删除集合中的项目,然后添加新项目以触发 UI 刷新。

If you replace the old observabel witha new one, the UI may not refresh.如果您用新的观察者替换旧的观察者,UI 可能不会刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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