Files
Jugenddienst-Stunden/Jugenddienst Stunden/Views/LoginPage.xaml.cs

87 lines
2.5 KiB
C#

using Jugenddienst_Stunden.Interfaces;
using Jugenddienst_Stunden.Models;
using Jugenddienst_Stunden.Types;
using Jugenddienst_Stunden.ViewModels;
using ZXing.Net.Maui;
namespace Jugenddienst_Stunden.Views;
/// <summary>
/// Die Loginseite mit dem Barcodescanner
/// </summary>
public partial class LoginPage : ContentPage {
/// <summary>
/// CTOR
/// </summary>
public LoginPage() {
InitializeComponent();
// BindingContext via DI beziehen, falls nicht bereits gesetzt
try {
if (BindingContext is null) {
var sp = Application.Current?.Handler?.MauiContext?.Services
?? throw new InvalidOperationException("DI container ist nicht verfügbar.");
BindingContext = sp.GetRequiredService<LoginViewModel>();
}
} catch (Exception) {
// Ignorieren: Fallback bleibt leerer BindingContext
}
if (BindingContext is LoginViewModel vm) {
vm.AlertEvent += async (_, msg) => await DisplayAlert("Fehler:", msg, "OK");
//vm.InfoEvent += async (_, msg) => await DisplayAlert("Information:", msg, "OK");
// Neues InfoEvent: Dialog anzeigen und nach Bestätigung das Result setzen
vm.InfoEvent += async (_, infoArgs) => {
await MainThread.InvokeOnMainThreadAsync(async () => {
await DisplayAlert(infoArgs.Title, infoArgs.Message, infoArgs.ConfirmText);
infoArgs.SetResult(true);
});
};
}
barcodeScannerView.Options =
new BarcodeReaderOptions { Formats = BarcodeFormat.QrCode, AutoRotate = true, Multiple = false };
// Fallback-Verkabelung: Falls das EventToCommandBehavior in XAML nicht greift,
// leiten wir das Kamera-Event manuell an das ViewModel-Command weiter.
barcodeScannerView.BarcodesDetected += (s, e) => {
if (BindingContext is LoginViewModel vm && vm.QrDetectedCommand is not null) {
// Sicherstellen, dass die Command-Ausführung im UI-Thread erfolgt
MainThread.BeginInvokeOnMainThread(async () => {
if (vm.QrDetectedCommand.CanExecute(e)) {
await vm.QrDetectedCommand.ExecuteAsync(e);
}
});
}
};
}
protected override void OnDisappearing() {
base.OnDisappearing();
barcodeScannerView.CameraLocation = CameraLocation.Front;
// Scanner deaktivieren, wenn Seite verlassen wird
if (BindingContext is LoginViewModel vm) {
vm.IsDetecting = false;
}
}
protected override void OnAppearing() {
base.OnAppearing();
if (BindingContext is LoginViewModel vm) {
vm.RefreshSettings();
// Scanner wieder aktivieren, wenn QR-Modus aktiv ist
vm.IsDetecting = !vm.IsManualMode;
}
barcodeScannerView.CameraLocation = CameraLocation.Rear;
}
}