Skip to content

Instantly share code, notes, and snippets.

@rupe120
Last active December 7, 2020 13:49
Show Gist options
  • Save rupe120/78f8a57f0ed7ecacbdc13fa2da8d931a to your computer and use it in GitHub Desktop.
Save rupe120/78f8a57f0ed7ecacbdc13fa2da8d931a to your computer and use it in GitHub Desktop.
ZXing scanner with Xamarin Forms FreshMVVM
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Pages.SearchQrPage"
xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
<ContentPage.Content>
<Grid>
<zxing:ZXingScannerView x:Name="scannerView" />
<zxing:ZXingDefaultOverlay x:Name="scannerOverlay"
TopText="Hold your phone up to the QR code"
BottomText="Scanning will happen automatically"
ShowFlashButton="True"/>
</Grid>
</ContentPage.Content>
</ContentPage>
using MyApp.PageModels;
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace MyApp.Pages
{
public partial class SearchQrPage : ContentPage
{
public SearchQrPage()
{
InitializeComponent();
scannerView.Options = new ZXing.Mobile.MobileBarcodeScanningOptions
{
PossibleFormats =
new List<ZXing.BarcodeFormat>
{
ZXing.BarcodeFormat.QR_CODE
}
};
scannerView.OnScanResult += ScannerView_OnScanResult;
scannerOverlay.FlashButtonClicked += ScannerOverlay_FlashButtonClicked;
}
protected override void OnAppearing()
{
scannerView.IsScanning = true;
base.OnAppearing();
}
private void ScannerOverlay_FlashButtonClicked(Button sender, EventArgs e)
{
scannerView.ToggleTorch();
}
private void ScannerView_OnScanResult(ZXing.Result result)
{
var model = this.BindingContext as SearchQrPageModel;
if (model == null)
return;
scannerView.IsScanning = false;
if (model.ScanResultCommand.CanExecute(result))
model.ScanResultCommand.Execute(result);
}
}
}
using FreshMvvm;
using MyApp.Infrastructure.Helpers;
using MyApp.Pages;
using System;
using System.ComponentModel;
using Xamarin.Forms;
namespace MyApp.PageModels
{
public class SearchQrPageModel : FreshBasePageModel, INotifyPropertyChanged
{
private bool NavigatingAway = false;
private Command<object> _scanResultCommand;
public Command<object> ScanResultCommand
{
get
{
return _scanResultCommand ?? (_scanResultCommand = new Command<object>(ScanResultAction));
}
}
protected override void ViewIsAppearing(object sender, EventArgs e)
{
NavigatingAway = false;
base.ViewIsAppearing(sender, e);
}
private void ScanResultAction(object obj)
{
// Prevent multiple event triggers from triggering the navigation multiple times
if (NavigatingAway)
return;
NavigatingAway = true;
var result = obj as ZXing.Result;
var format = result?.BarcodeFormat.ToString() ?? string.Empty;
var value = result?.Text ?? string.Empty;
Device.BeginInvokeOnMainThread(async () =>
{
// Navigate to a page based on value
}
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment