0

By the moment I am using the scanner in code behind in this way:

View:

    <zxing:ZXingScannerView x:Name="ucZXingScannerView" IsScanning="True" IsAnalyzing="True" ScanResultCommand="{Binding CodigoQr, Mode=TwoWay}" OnScanResult="ucZXingScannerView_OnScanResult" />

Code behind: 

        void ucZXingScannerView_OnScanResult(ZXing.Result result)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        ScannerViewModel miViewModel = this.BindingContext as ScannerViewModel;

        miViewModel.CodigoQr = result.Text + " (type: " + result.BarcodeFormat.ToString() + ")";

        ucZXingScannerView.IsScanning = false;
        ucZXingScannerView.IsAnalyzing = false;
    });
}

But I would like to avoid to have code in the code behind, so I am trying this:

View:

<zxing:ZXingScannerView x:Name="ucZXingScannerView" IsScanning="True" IsAnalyzing="True" ScanResultCommand="{Binding CodigoQr, Mode=TwoWay}" OnScanResult="{Binding ResultadoQrCommand}" />

View Model:

public Command<ZXing.Result> ResultadoQrCommand { get; private set; }

private void OnresultadoQr(ZXing.Result paramResultado)
{
    CodigoQr = "Prueba";
}

But in this case a get an error in the xaml code that tells "event OnScanResult can only bound to properties of delegate ScanResultDelegate".

My command in the view model has the same parameters that the method of the code behind and I don't be able to find the solution.

How could I define the command in the view model to can bind to the view model?

EDIT: according to the suggestion from Jason, I have tried this code:

The view:

<zxing:ZXingScannerView x:Name="ucZXingScannerView" IsScanning="True" IsAnalyzing="True" ScanResultCommand="{Binding ScanResultCommand}" />

The view model:

public ScannerViewModel()
{
    ScanResultCommand = new Command<ZXing.Result>((x) => OnScanResultCommand(x), (x) => true);
}

public Command<ZXing.Result> ScanResultCommand { get; private set; }

private void OnScanResultCommand(ZXing.Result paramResultado)
{
    CodigoQr = paramResultado.Text;
}

But the command is not rised.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    if you want to use a Command, bind a command to `ScanResultCommand`, do not use the `OnScanResult` event – Jason Apr 29 '21 at 16:31
  • Thanks so much for the help. I remove the event and I added the command, but it is not rised. I have added the code in the original post, at the end. – Álvaro García Apr 29 '21 at 18:46
  • @ÁlvaroGarcía can not find any problem form your code, but you can take a look [this thread](https://forums.xamarin.com/discussion/156446/how-do-i-scan-with-zxingscannerview-using-mvvm-pattern-updated-with-code) about `ScanResultCommand` – Cherry Bu - MSFT Apr 30 '21 at 02:12

0 Answers0