You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Xamarin转MAUI:ZXing.Net.MAUI是否有类似MobileBarcodeScanner的扫描功能?

在MAUI中使用ZXing.Net.MAUI实现弹出式条码扫描

ZXing.Net.MAUI支持和你原来Xamarin项目中类似的弹出式扫描功能,不需要强制创建嵌入视图,下面是对应实现:

1. 基础弹出式扫描(和原逻辑一致)

首先确保已安装ZXing.Net.MAUI NuGet包,然后在MauiProgram.cs中注册服务:

builder.Services.AddZXingNetMobile();

接着在页面代码后台通过依赖注入获取扫描服务,实现扫描逻辑:

private readonly IBarcodeScanner _barcodeScanner;

// 构造函数注入扫描服务
public YourPage(IBarcodeScanner barcodeScanner)
{
    InitializeComponent();
    _barcodeScanner = barcodeScanner;
}

async void OnScanButtonClickedL10(object sender, EventArgs e)
{
    var scanResult = await _barcodeScanner.ScanAsync();

    if (scanResult != null && !string.IsNullOrWhiteSpace(scanResult.Text))
    {
        txtL10EanCode.Text = scanResult.Text;
    }
}

如果不想用依赖注入,也可以直接通过BarcodeScanner.Default获取实例,不过依赖注入更符合MAUI的设计规范。

2. 自定义嵌入视图(可选)

如果需要定制扫描界面(比如添加自定义控件、调整扫描框样式),才需要创建BarcodeReaderView嵌入到页面中:
在XAML中添加扫描视图:

<zxing:BarcodeReaderView 
    x:Name="CustomBarcodeReader"
    IsScanning="False"
    IsDetecting="True"
    WidthRequest="350"
    HeightRequest="350"
    BarcodesDetected="CustomBarcodeReader_BarcodesDetected" />

代码后台处理扫描结果:

private void CustomBarcodeReader_BarcodesDetected(object sender, BarcodeDetectedEventArgs e)
{
    var firstResult = e.Results.FirstOrDefault();
    if (firstResult != null)
    {
        // 必须通过Dispatcher更新UI,因为扫描事件在后台线程触发
        Dispatcher.Dispatch(() =>
        {
            txtL10EanCode.Text = firstResult.Text;
            CustomBarcodeReader.IsScanning = false;
        });
    }
}

// 启动扫描的按钮事件
async void OnScanButtonClickedL10(object sender, EventArgs e)
{
    CustomBarcodeReader.IsScanning = true;
}

内容的提问来源于stack exchange,提问作者Giorgio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:42:17