xaml – OnAppearing事件触发两次.with标签页

我面临的问题是Xamarin表单和MVVM的初学者.我有标签页,标签下有2页.这是代码.

    

          

          

      

问题是本地的:ActiveOrderViewPage页面OnAppearing()事件在tabbedPage加载时触发两次,并在OnAppearing()事件下执行两次代码.

请帮我找到这个为什么会这样?

这是代码选项卡页面
 tabbedpage.xaml

<TabbedPage
        xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        Title="Orders">
<TabbedPage.Children>  
      <local:ActiveOrderViewPage />  
      <local:SavedOrderViewPage />
</TabbedPage.Children>

tabbedpage.xaml.cs

  public partial class OrderTabViewPage : TabbedPage
{
    public OrderViewModel ViewModel { get { return BindingContext as OrderViewModel; } }
    public OrderTabViewPage()
    {
        InitializeComponent();
     this.BindingContext = ViewModelLocator.OrderVModel;

    }
    public OrderTabViewPage(params object[] arg) : this()
    {
        if (arg != null)
        {
            ViewModel.AccountID = Convert.ToInt32(arg[0]);
        }
    }

这是有效订单.cs

 public partial class ActiveOrderViewPage : ContentPage
{
    public OrderViewModel ViewModel { get { return BindingContext as OrderViewModel; } }
    public ActiveOrderViewPage()
    {
        InitializeComponent();
      this.BindingContext = ViewModelLocator.OrderVModel;       
    }

    //public OrderViewPage() : this()
    //{
    //    ViewModel.AccountID = accuntId;
    //}
    protected override void OnAppearing()
    {
        base.OnAppearing();
        if (ViewModelLocator.OrderVModel.ActiveOrderItems == null || ViewModelLocator.OrderVModel.ActiveOrderItems.List.Count == 0)
        {
            ViewModelLocator.OrderVModel.ActiveOrderCommand.Execute(null);
        }


    }

提前致谢 …

最佳答案 很长一段时间遇到这个问题,在意识到之前,我知道这是多么令人沮丧.由于选项卡式页面呈现所有单个页面的方式,OnAppearing()事件会触发两次.它最初呈现页面,然后在您的情况下将呈现另一页,这将导致OnDisappearing()触发.然后第一页获得焦点,导致OnAppearing()再次触发.

如果您只希望代码触发一次,在添加子页面后,将currentpage属性设置为null,这应该会停止OnAppearing()再次触发

点赞