【问题标题】:Barcode scanning using zxing使用 zxing 进行条码扫描
【发布时间】:2021-04-05 12:51:26
【问题描述】:

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

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

【问题讨论】:

  • 使用 EventToCommand 行为,或者只是让事件处理程序调用您的 VM 方法。使用事件不一定会破坏 MVVM

标签: xamarin.forms zxing.net


【解决方案1】:

如果您不想使用行为,只需创建一个新版本的 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}" />

祝你好运

如有疑问,请随时回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2013-05-25
    • 1970-01-01
    相关资源
    最近更新 更多