从xamarin android导航到PCL

时间:2016-02-23 13:53:46

标签: xamarin xamarin.forms

我目前正在使用带有PCL的xamarin表格来访问相机和扫描条形码并在UserDialog中显示它。我可以使用依赖服务轻松地做到这一点。我遇到的问题是回归。我想通过按userDialog上的取消按钮返回PCL。我正在使用messagingcenter返回到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"); });

        }
    });
}

2 个答案:

答案 0 :(得分:2)

在这种情况下,我真的很想使用async/await语法:

1)在班级TaskCompletionSource<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();

答案 1 :(得分:0)

@Eugene解决方案很棒,但您仍然可以使用消息中心:

我认为问题就在这里:

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.
});