使用zxing进行条码扫描

时间:2020-12-28 19:18:24

标签: xamarin.forms zxing.net

<zxing:ZXingScannerView IsScanning="True" OnScanResult="OnScanResult"/> 我在 xaml 文件中有这个,但我想使用 mvvm,所以我在视图模型中有 onscanresult 事件处理程序。我怎样才能使用它而不是后面代码中的那个?

public void OnScanResult(ZXing.Result result)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        ScanResult = result.Text + " (type: " + result.BarcodeFormat + ")";
    });
}

1 个答案:

答案 0 :(得分:0)

如果您不想使用行为,只需创建一个新版本的 ContentPage 来创建一个要命令的事件:

    public class ZxingContentPage : ZXingScannerPage
{
    public static readonly BindableProperty ScanResultCommandProperty =
        BindableProperty.Create(
            nameof(ScanResultCommand),
            typeof(ICommand),
            typeof(ZxingContentPage),
            default(ICommand)
            );

    public ICommand ScanResultCommand
    {
        get { return (ICommand)GetValue(ScanResultCommandProperty); }
        set { SetValue(ScanResultCommandProperty, value); }
    }

    public ZxingContentPage(MobileBarcodeScanningOptions options) : base(options)
    {
        OnScanResult += ZxingContentPage_OnScanResult;
    }

    private void ZxingContentPage_OnScanResult(ZXing.Result result)
    {
        if (ScanResultCommand?.CanExecute(result) == true)
        {
            ScanResultCommand.Execute(result);
        }
    }
}

然后像下面这样使用它:

<?xml version="1.0" encoding="utf-8" ?>
<views:ZxingContentPage
  x:Class="NameSpace.Zxing.ZxingMobileScannerView"
  xmlns="http://xamarin.com/schemas/2014/forms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:views="clr-namespace:QRST.Views.Generic"
  IsScanning="True"
  ScanResultCommand="{Binding ZxingScanResultCommand}" />

祝你好运

如有疑问,请随时回复。