【问题标题】:ViewModel's properties become null when navigatingViewModel 的属性在导航时变为 null
【发布时间】:2018-02-25 15:07:02
【问题描述】:

我有两个页面,它们共享同一个 ViewModel。我这样做是为了在从 Page1 导航到 Page2 时处理相同的数据。 当我导航到 Page2 时,我需要的数据是绑定到 ViewModel 的第 1 页条目的文本。 Page1 构造函数:

        public Page1()
        {
            InitializeComponent();
            this.BindingContext = new ViewModel(this.Navigation);
        }

在第 1 页的 XAML 中:

<Entry Text="{Binding Entry1TextFromPage1}"/>
<Entry Text="{Binding Entry2TextFromPage1}"/>

在我做的 ViewModel 中:

        public ViewModel(INavigation navigation)
        {
            this.Navigation = navigation;
            this.ButtonOnPage1Command = new Command( async () =>
                await this.Navigation.PushAsync(new Page2());
            );
            this.ButtonOnPage2Command = new Command( async () =>
                Use(this.Entry1TextFromPage1); //Here the text is null
                Use(this.Entry2TextFromPage1); //Here the text is null
            );
        }

所有绑定的文本条目(来自 Page1)都变为空。我错过了什么?

【问题讨论】:

  • 请出示相关代码!
  • 你如何共享虚拟机?当您调用 Page2 时,您实际上是在将 ref 传递给 VM 吗?还是 Page2 创建它自己的实例?

标签: xamarin mvvm xamarin.forms


【解决方案1】:

您的 Page2 可能没有将其 BindingContext 设置为相同的 ViewModel。将您的 ViewModel 作为参数传递给 Page2 构造函数,因此您可以这样称呼它PushAsync(new Page2(this))

public Page2(ViewModel viewModel)
{
    InitializeComponent();
    BindingContext = viewModel;
}

【讨论】:

  • 谢谢,我犯了一个愚蠢的错误。现在我什至不需要一个 ViewModel,每个页面都有一个,因为我可以通过构造函数在 ViewModel 之间传递数据。
猜你喜欢
  • 2022-09-23
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多