6

New to Xamarin development! Using Visual Studio 2017 and all the latest installs and updates for my dev environment.

I have my app "shell" working in that it will run, navigate, crud to local db, and sync to rest services. So, the base of my app is sound. I am trying to integrate the ZXing barcode scanner into my app. Most of what help I can find relates to raw forms or code behind xaml. I am using views and view models and I don't know how to translate the information I am finding to this model.

I currently have the xaml view showing the "camera viewer" when a button is clicked so I can see a barcode using the camera. However, there is no "red line" in the camera view and subsequently, there are no events being fired to let me know what is going on. I really am confused as I am so new to Xamarin. I don't know where to start.

XAML View page

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
         xmlns:fe="clr-namespace:FreshEssentials;assembly=FreshEssentials"
         xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
         prism:ViewModelLocator.AutowireViewModel="True"
         x:Class="Views.InventoryPage1"
    Title="Inventory Page">

<StackLayout Spacing="5" Padding="10,10,10,0">
    <!--<fe:BindablePicker ItemsSource="{Binding Areas}" SelectedItem="{Binding SelectedArea}" DisplayProperty="AreaName" Title="Select Your Area" />
    <fe:BindablePicker ItemsSource="{Binding Reasons}" SelectedItem="{Binding SelectedReason}" 
        DisplayProperty="Description" Title="Select a Reason" />
    <Label Text="Scan"/>
    <Entry Text="{Binding Barcode}"/>
    <Label Text="Quantity"/>
    <Entry Text="{Binding Quantity}"/>
    <Button Text="Save" Style="{StaticResource Button_Primary}" Command="{Binding SaveCommand}" />-->

    <forms:ZXingScannerView WidthRequest="100" HeightRequest="100" IsScanning="{Binding IsScanning}" IsAnalyzing="{Binding IsAnalyzing}" Result="{Binding Result, Mode=TwoWay}" ScanResultCommand="{Binding QRScanResultCommand}" ></forms:ZXingScannerView>
    </StackLayout>
</ContentPage>

ViewModel

public class InventoryPage1ViewModel : BindableBase, INavigationAware
{
    private readonly IPageDialogService _pageDialogService;
    private bool _isAnalyzing = true;
    private bool _isScanning = true;
    public ZXing.Result Result { get; set; }

    public List<Area> Areas { get; private set; }
    public Area SelectedArea { get; set; }

    public List<Reason> Reasons { get; private set; }
    public Reason SelectedReason { get; set; }

    public int Quantity { get; set; }
    public string Barcode { get; set; }

    public DelegateCommand SaveCommand => new DelegateCommand(PerformSave);
    public DelegateCommand QRScanResultCommand => new DelegateCommand(QRCommand);

    private readonly IAreaService _areaService;
    private readonly IScanService _scanService;
    private readonly IReasonService _reasonService;

    public InventoryPage1ViewModel(IAreaService areaService, IScanService scanService, IReasonService reasonService, IPageDialogService pageDialogService)
    {
        _pageDialogService = pageDialogService;
        _reasonService = reasonService;
        _scanService = scanService;
        _areaService = areaService;
        Areas = _areaService.GetAll();
        Reasons = _reasonService.GetAll();
    }

    public bool IsScanning
    {
        get
        {
            return _isScanning;
        }
        set
        {
            _isScanning = value;
            RaisePropertyChanged();
        }
    }

    public bool IsAnalyzing
    {
        get
        {
            return _isAnalyzing;
        }
        set
        {
            _isAnalyzing = value;
            RaisePropertyChanged();
        }
    }

    private void QRCommand()
    {
        int x = 1;
    }

    private async void PerformSave()
    {
        var scan = new Scan()
        {
            AreaId = SelectedArea.Id,
            InsertDateTime = DateTime.Now,
            ReasonId = SelectedReason.Id,
            ScanItem = Barcode,
            ScanQty = Quantity,
            IsUploaded = false
        };

        // Save it to the DB here.
        var retVal = _scanService.Insert(scan);

        if (retVal)
        {
            await _pageDialogService.DisplayAlertAsync("Saved", "Scan saved successfully.", "OK");
        }
        else
        {
            // TODO: Inform the user something went wrong.
        }
    }

    int _index;
    public int SelectIndex
    {
        get
        {
            return _index;
        }
        set
        {
            _index = value;
            RaisePropertyChanged("SelectIndex");
        }
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {
    }

    public void OnNavigatedTo(NavigationParameters parameters)
    {
    }

    public void OnNavigatingTo(NavigationParameters parameters)
    {
    }
}

MainActivity

public class MainActivity : 
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.tabs;
        ToolbarResource = Resource.Layout.toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        ZXing.Net.Mobile.Forms.Android.Platform.Init();

        LoadApplication(new App(new AndroidInitializer()));

    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
    {
        ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

public class AndroidInitializer : IPlatformInitializer
{
    public void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IConnectionFactory, ConnectionFactory>();
    }
}

UPDATE I have a working view model now thanks to @Krzysztof over at Xamarin.Forms.

New ViewModel

public class InventoryPage1ViewModel : BindableBase, INavigationAware
{
    private readonly IPageDialogService _pageDialogService;
    public List<Area> Areas { get; private set; }
    public Area SelectedArea { get; set; }

    public List<Reason> Reasons { get; private set; }
    public Reason SelectedReason { get; set; }

    public int Quantity { get; set; }

    public DelegateCommand SaveCommand => new DelegateCommand(PerformSave);

    private readonly IAreaService _areaService;
    private readonly IScanService _scanService;
    private readonly IReasonService _reasonService;

    public InventoryPage1ViewModel(IAreaService areaService, IScanService scanService, IReasonService reasonService, IPageDialogService pageDialogService)
    {
        _pageDialogService = pageDialogService;
        _reasonService = reasonService;
        _scanService = scanService;
        _areaService = areaService;
        Areas = _areaService.GetAll();
        Reasons = _reasonService.GetAll();
    }

    public ZXing.Result Result { get; set; }

    private string barcode = string.Empty;
    public string Barcode
    {
        get
        {
            return barcode;
        }
        set
        {
            barcode = value;
            RaisePropertyChanged();
        }
    }

    private bool isAnalyzing = true;
    public bool IsAnalyzing
    {
        get { return this.isAnalyzing; }
        set
        {
            if (!bool.Equals(this.isAnalyzing, value))
            {
                this.isAnalyzing = value;
                RaisePropertyChanged(nameof(IsAnalyzing));
            }
        }
    }

    private bool isScanning = true;
    public bool IsScanning
    {
        get { return this.isScanning; }
        set
        {
            if (!bool.Equals(this.isScanning, value))
            {
                this.isScanning = value;
                RaisePropertyChanged(nameof(IsScanning));
            }
        }
    }

    public Command QRScanResultCommand
    {
        get
        {
            return new Command(() =>
            {
                IsAnalyzing = false;
                IsScanning = false;

                Device.BeginInvokeOnMainThread(async () =>
                {
                    Barcode = Result.Text;
                    await _pageDialogService.DisplayAlertAsync("Scanned Item", Result.Text, "Ok");
                });

                IsAnalyzing = true;
                IsScanning = true;
            });
        }
    }
    private async void PerformSave()
    {
        var scan = new Scan()
        {
            AreaId = SelectedArea.Id,
            InsertDateTime = DateTime.Now,
            ReasonId = SelectedReason.Id,
            ScanItem = Barcode,
            ScanQty = Quantity,
            IsUploaded = false
        };

        // Save it to the DB here.
        var retVal = _scanService.Insert(scan);

        if (retVal)
        {
            await _pageDialogService.DisplayAlertAsync("Saved", "Scan saved successfully.", "OK");
        }
        else
        {
            // TODO: Inform the user something went wrong.
        }
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {
    }

    public void OnNavigatedTo(NavigationParameters parameters)
    {
    }

    public void OnNavigatingTo(NavigationParameters parameters)
    {
    }
}
BTI-Doug
  • 455
  • 1
  • 6
  • 17

0 Answers0