Search code examples
xamarinxamarin.formszxing.net.mobile

zxing qr/barcode scanning using MVVM?


Im new in xamarin, Im trying to make a Button that opens a scanner form that scans qr/barcode that is MVVM method. Im trying to get the result and display it into a label. this is my best guest but it doesn't work, hope someone can help.

view:
<StackLayout>
 <Label Text="{Binding CodigoQr}"/>
 <zxing:ZXingScannerView x:Name="ucZXingScannerView" 
  IsScanning="True" 
  IsAnalyzing="True"
  Result="{Binding CodigoQr}"
  ScanResultCommand="{Binding ScanCommand }" />
 </StackLayout>

ViewModel:
public class BarcodeScanVM : BaseViewModel
    {
        private Result _codigoQr;
        public Result CodigoQr
        {
            get { return _codigoQr; }
            set
            {
                _codigoQr = value;
                OnPropertyChanged();
            }
        }
        public AsyncCommand ScanCommand { get; set; }
        public BarcodeScanVM()
        {
            ScanCommand = new AsyncCommand(OnScanResultCommand);
        }
        async Task OnScanResultCommand()
        {
            var text = CodigoQr;
        }
    }```

Solution

  • You can use the code-behind the view for the actions. And use the VM for other properties

    XAML:

     <zxing:ZXingScannerView
            IsAnalyzing="{Binding IsAnalyzing}"
            IsScanning="{Binding IsScanning}"
            OnScanResult="CameraScanner_OnScanResult" />
    

    Code behind:

    private void CameraScanner_OnScanResult(ZXing.Result result)
            {   
                 ((MyViewModel)BindingContext).OnScanComplete(result.Text);
            }