如何将方法转换为事件?

时间:2017-10-05 09:19:27

标签: c# xamarin.forms barcode-scanner manateeworks

如何将此方法用于事件?

BarcodeScannerRenderer.cs:

void IScanSuccessCallback.barcodeDetected(MWResult result)
{
   if (result != null)
   {
       try
       {
           var scan = Element as BarcodeScannerModal;
           if (scan == null)
           return;
       }
       catch (Exception ex)
       {
           System.Diagnostics.Debug.WriteLine(ex.Message);
       }
   }
}

并将结果的值传递给另一个类,特别是在这里:

(适用BarcodeScanner.cs)

public async Task<object[]> GetResult()
    {
        TaskCompletionSource<object[]> tcs = new TaskCompletionSource<object[]>();
        scanPage.OnScanResult += async (result) =>
        {
            object[] scanResult = new object[2];
            SharedAppSettings.Sounds.PlayBeep();
            scanResult[0] = resultFinal.text;
            scanResult[1] = resultFinal.typeText;
            await PopupNavigation.PopAsync();

            tcs.SetResult(scanResult);
        };
        return await tcs.Task;
    }

如果您想知道我使用的是什么类型的条码扫描器,它是Manatee Works条码扫描器。

1 个答案:

答案 0 :(得分:1)

这个答案可能必须适应问题的变化,所以不要认为它完整:

要举办活动,您可以这样做:

// Given you have a custom EventArgs class ...
// Define an event on which clients can register their handlers
public event EventHandler<BCDetectedEventArgs> BarcodeDetected;

// infoObject should probably be of the type what `scan` is.
protected virtual void OnBarcodeDetected( object infoObject ) 
{
    // Check if there is at least one handler registered
    var handler = BarcodeDetected;
    if( handler != null )
    {

         handler(this, new BCDetectedEventArgs(infoObject));
    }
}

void IScanSuccessCallback.barcodeDetected(MWResult result)
{
   if (result != null)
   {
       try
       {
           var scan = Element as BarcodeScannerModal;
           if (scan == null)
              return;
           else
              OnBarcodeDetected( scan );
       }
       catch (Exception ex)
       {
           System.Diagnostics.Debug.WriteLine(ex.Message);
       }
   }
}

另请参阅参考https://msdn.microsoft.com/en-us/library/db0etb8x(v=vs.110).aspx

BarcodeScanner.cs中的部分有点棘手,因为您的代码片段暗示了“轮询”设计。您首先必须适应从上面的代码段注册到事件,并以适当的处理程序方法对事件进行操作。