Home > Software engineering >  zxing qr/barcode scanning using MVVM?
zxing qr/barcode scanning using MVVM?

Time:12-23

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;
        }
    }```

CodePudding user response:

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);
        }

CodePudding user response:

update: I tried this one, seems like the scanning command works but the program stops afterwards.

ViewMode:
private Result bcScanResult;
    public Result BcScanResult
    {
        get => bcScanResult;
        set
        {

            if (value == bcScanResult)
                return;
            bcScanResult = value;
            OnPropertyChanged();
        }
    }

  public AsyncCommand BcScanCommand { get; }

  public CodeScanVM()
    {
        BcScanCommand = new AsyncCommand(BcScanCommand_Call);
    }

  async Task BcScanCommand_Call()
    {
        await App.Current.MainPage.DisplayAlert("Item", "Code Async 
        Command:"   Result, "OK");
        return;
    }

 View:
 <zxing:ZXingScannerView
            x:Name="ScanView"
            Result="{Binding BcScanResult}"
            ScanResultCommand="{Binding BcScanCommand }"
            IsScanning="True"
            WidthRequest="300"
            HeightRequest="300"/>
  • Related