How to activate camere when changing tab in .net maui

Rendy Putrayana 0 Reputation points
2025-02-13T07:16:56.0133333+00:00

I'm developing a .NET MAUI application using MVVM for learning, and I have a BarcodePage that contains a CameraBarcodeReaderView (from ZXing.Net.Maui.Control). Everything works fine when I first navigate to the page, but when I navigate away and then return, the barcode reader view turns black and doesn't work.

Here’s how I initialize the camera in BarcodePage.xaml.cs:

using Item_Barcode_Scanning.ViewModel;

using ZXing.Net.Maui;

using ZXing.Net.Maui.Controls;

namespace Item_Barcode_Scanning.View;

public partial class BarcodePage : ContentPage

{

public BarcodePage()

{

	InitializeComponent();

    BindingContext = new BarcodeViewModel();

    CameraBarcodeReaderView.Options = new BarcodeReaderOptions()

    {

        Formats = ZXing.Net.Maui.BarcodeFormat.Code128,

        AutoRotate = true,

        Multiple = false,

        TryHarder = true,

    };

}

}

here is my viewmodel

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using CommunityToolkit.Mvvm.ComponentModel;

using CommunityToolkit.Mvvm.Input;

using ZXing.Net.Maui;

using ZXing.QrCode.Internal;

namespace Item_Barcode_Scanning.ViewModel

{

public partial class BarcodeViewModel : ObservableObject

{

    [ObservableProperty]

    private string barcode;

    [RelayCommand]

    async Task ReadBarcode(BarcodeDetectionEventArgs e)

    {

        if (e.Results != null)

        {

            string scannedBarcode = e.Results[0].Value;

            await MainThread.InvokeOnMainThreadAsync(async () =>

            {

                Barcode = scannedBarcode;

                await Shell.Current.DisplayAlert("Barcode Detected", scannedBarcode, "OK");

            });

        }

    }

}

}

Developer technologies .NET .NET MAUI
Developer technologies .NET Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2025-02-14T03:03:23.81+00:00

    Hello,

    This is because the page in the Shell is navigated through the singleton mode, and when returning to the BarcodePage, the Shell will only reuse it without rebuilding it. This leads to the problem of no content in the CameraView.

    Workaround: By executing the page's rebuild method in the navigation method.

    In shell:

    <ShellContent Route="camerapage" ContentTemplate="{DataTemplate local:MainPage}" />
    public partial class AppShell : Shell
    {
        public AppShell()
        {
            InitializeComponent();
        }
        protected override void OnNavigated(ShellNavigatedEventArgs args)
        {
            string local = args.Current.Location.ToString();
            if (local.Contains("camerapage"))
            {
                MainPage.RecreateMainPage(); // recreate the page
            }
            base.OnNavigated(args);  
        }
    }
    

    In mainpage:

    public partial class MainPage : ContentPage
    {
        int count = 0;
        public static MainPage Instance{ get; private set; }
        public MainPage()
        {
            InitializeComponent();
            BindingContext = new BarcodeViewModel();
            Instance = this;
        }
        public static void RecreateMainPage()
        {
            MainPage.Instance.Content = null;
            VerticalStackLayout views = new VerticalStackLayout();
            var CameraBarcodeReaderView = new CameraBarcodeReaderView();
            CameraBarcodeReaderView.Options = new BarcodeReaderOptions()
            {
                Formats = ZXing.Net.Maui.BarcodeFormat.Code128,
                AutoRotate = true,
                Multiple = false,
                TryHarder = true,
            };
            views.Add(CameraBarcodeReaderView);
            MainPage.Instance.Content = views;
        }
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.