从 xamarin android 导航到 PCL

Navigating from xamarin android to PCL

我目前正在使用带有 PCL 的 xamarin 表单来访问相机和扫描条形码并将其显示在 UserDialog 中。我可以使用依赖服务轻松做到这一点。我遇到的问题是回去。我想通过按 userDialog 上的取消按钮返回 PCL。我正在使用消息中心返回 PCL 主页,消息确实返回了,但 UI 保持不变,即相机屏幕保持在那里。

下面是我的代码

void HandleScanResult(ZXing.Result result)
{
    if (result != null && !string.IsNullOrEmpty(result.Text))
    {
        CrossVibrate.Current.Vibration(500);
    }

    Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
    {
        resultText.Text = await SaveScannedRecord(result.Text);
        PromptResult promptResult = await UserDialogs.Instance.PromptAsync
        ("Hello Friends","Question","SCAN","CANCEL",resultText.Text,InputType.Name);     
        if (promptResult.Ok)
        {

        }
        else
        {
            //CODE TO GO BACK
            var home = new Home();
            RunOnUiThread(() => { xamarinForm.MessagingCenter.Send<Home>(home, "scannedResult"); });

        }
    });
}

在这种情况下,我非常喜欢使用 async/await 语法:

1) 在classTaskCompletionSource<bool>变量的某处定义

2) 当您调用您的方法时,初始化该变量:

public async Task<bool> Scan()
{
   // init task variable
   tsc = new TaskCompletionSource<bool>();

   // call your method for scan (from ZXing lib)
   StartScan(); 

   // return task from source
   return tsc.Task;
}

3) 处理结果时,为任务设置结果:

void HandleScanResult(ZXing.Result result)
{
   Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
   {
       resultText.Text = await SaveScannedRecord(result.Text);
       PromptResult promptResult = await UserDialogs.Instance.PromptAsync("Hello Friends", "Question", "SCAN", "CANCEL", resultText.Text, InputType.Name);
       if (promptResult.Ok)
       {
         tsc.SetResult(true);
       }
       else
       {
         //CODE TO GO BACK
         tsc.SetResult(false);
       }
    });    
}

现在你可以在PCL中编写导航逻辑了,像这样:

var scanResult = await scanService.Scan();
if (!scanResult)
   // your navigation logic goes here
   Navigation.PopToRoot();

@Eugene Solution 很棒,不过你仍然可以使用消息中心:

我认为问题就在这里:

xamarinForm.MessagingCenter.Send<Home>(home, "scannedResult"); });

//Solution:
MessagingCenter.Send<Home> (this, "scannedResult");
//Inside the PCL you will need:
MessagingCenter.Subscribe<Home> (this, "scannedResult", (sender) => {
    // do your thing.
});