使用zxing进行条形码扫描



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

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

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

祝好运

如有疑问,请随时回复。

最新更新