How to use ZXing in MVVM?

698 views Asked by At

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.

0

There are 0 answers