在OnBackButtonPressed上显示操作表

时间:2018-01-13 06:32:20

标签: c# xamarin.forms

我正在使用PCL创建xamarin表单。我想在用户从移动设备硬件按后退按钮然后我想要DispalyActionSheet时提供一项功能。我可以做任何选择。以下是我的示例代码。

    protected override bool OnBackButtonPressed()
    {
        base.OnBackButtonPressed();

        //new thread
        Device.BeginInvokeOnMainThread(async () =>
        {
              var action = await DisplayActionSheet("ActionSheet: Send to?", "Cancel", null, "Facebook", "twitter", "Instagram");

      //  Here i want to get  action  result for next step
        });

        return true; // 
    }

根据Martin Zikmund建议的代码更新:代码执行后在不同页面上重定向感觉很困难

 protected override bool OnBackButtonPressed()
        {
            bool returnvalue = true;

            Device.BeginInvokeOnMainThread(async () =>
            {
              vawait DisplayActionSheet("ActionSheet: Send to?", "null", null, "Facebook", "twitter", "Instagram");
                    switch (action)
                    {
                        case "Facebook":
                         // My code
                CallPage();  Here i want to redirect on different page 
               break;
                    }
            });
      }


 public async void CallPage()
    {
        try
        {
            await RetrunToPreviousPage();
        }
        catch (Exception ex)
        {

            //throw;
        }
    }

  public async Task<dynamic> RetrunToPreviousPage()
    {

            Navigation.InsertPageBefore(new InboundOrderList(), this);
            await Navigation.PopAsync();            

        return true;
    }

1 个答案:

答案 0 :(得分:1)

如果您想自己处理后退按钮,则需要移除对base.OnBackButtonPressed的呼叫。

protected override bool OnBackButtonPressed()
{        
    Device.BeginInvokeOnMainThread(async () =>
    {
          var action = await DisplayActionSheet(
            "ActionSheet: Send to?", "Cancel", null, "Facebook", "twitter", "Instagram");

          //your logic             
    });

    return true; //you handled the back button press
}

如果您真的想要在逻辑中导航回来,则必须手动弹出堆栈页面:

await this.Navigation.PopAsync();

更新

您仍然必须在true的末尾返回OnBackButtonPressed以将其标记为已处理。此外,ReturnToPreviousPage不需要任何return true;,返回类型可以是简单的Task

protected override bool OnBackButtonPressed()
    {
        bool returnvalue = true;

        Device.BeginInvokeOnMainThread(async () =>
        {
          vawait DisplayActionSheet("ActionSheet: Send to?", "null", null, "Facebook", "twitter", "Instagram");
                switch (action)
                {
                    case "Facebook":
                     // My code
            CallPage();  Here i want to redirect on different page 
           break;
                }
        });
      return true; // always return true
  }

  ...

  public async Task RetrunToPreviousPage()
  { 
      Navigation.InsertPageBefore(new InboundOrderList(), this);
      await Navigation.PopAsync();            
  }