2016-02-23 62 views
0

我目前在PCL中使用xamarin格式來訪問攝像頭並掃描條形碼並將其顯示在UserDialog中。我可以使用依賴服務輕鬆完成。我遇到的問題正在迴歸。我想通過按下userDialog上的取消按鈕回到PCL。我正在使用messagingcenter返回PCL主頁,並且消息會返回,但UI保持不變,即相機屏幕停留在那裏。從xamarin android導航到PCL

下面是我的代碼

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

     } 
    }); 
} 
+0

發送消息給anothe r頁面只會發送一條消息:當您收到解除掃描儀頁面的消息時,您需要執行一些操作。你如何做到這一點將取決於你如何展示它。你也有RunOnUIThread嵌套在BeginInvokeOnMainThread內,這是不必要的。最後,你應該可以直接從PCL調用ZXIng。請參閱github頁面,瞭解這樣做的Forms示例應用程序。 – Jason

+0

你如何解僱掃描儀頁面。 – maxspan

+0

這取決於 - 你沒有顯示實際顯示頁面的代碼。 – Jason

回答

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(); 
+0

我試過你的代碼。但它確實返回到PCL頁面。 – maxspan

+0

@maxspan在「代碼返回」部分有錯誤。應該是tsc.SetResult(false)。另外,我真的不明白你想達到什麼目的。我只想指出,有一種方法可以將導航邏輯移動到PCL – Eugene

0

@Eugene解決方案是一個偉大的,但你仍然可以使用Messaging中心:

我相信問題就在這裏:

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

我已經試過它不工作。此外,我正在使用不斷的掃描。 – maxspan