Utopia-Canteen-System/Views/AdminLoginView.xaml.cs

112 lines
3.4 KiB
C#

using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using UtopiaCanteenSystem.ViewModels;
namespace UtopiaCanteenSystem.Views;
/// <summary>
/// Minimal code-behind for PasswordBox + initial focus.
/// </summary>
public partial class AdminLoginView : UserControl
{
private AdminLoginViewModel? _vm;
public AdminLoginView()
{
InitializeComponent();
Loaded += OnLoaded;
DataContextChanged += OnDataContextChanged;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
// If VM has a remembered password, prefill the PasswordBox (it's not bindable).
if (DataContext is AdminLoginViewModel vm && !string.IsNullOrEmpty(vm.Password))
PasswordBox.Password = vm.Password;
TryLoadLogo();
UsernameTextBox.Focus();
UsernameTextBox.SelectAll();
}, DispatcherPriority.Input);
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_vm != null)
_vm.PropertyChanged -= VmOnPropertyChanged;
_vm = DataContext as AdminLoginViewModel;
if (_vm != null)
_vm.PropertyChanged += VmOnPropertyChanged;
// Sync PasswordBox from VM when navigating here (supports remembered creds).
if (_vm != null)
PasswordBox.Password = _vm.Password ?? string.Empty;
}
private void VmOnPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (!string.Equals(e.PropertyName, nameof(AdminLoginViewModel.Password), StringComparison.Ordinal))
return;
// Keep PasswordBox UI in sync when VM clears password after clicking Login.
if (_vm != null && string.IsNullOrEmpty(_vm.Password) && !string.IsNullOrEmpty(PasswordBox.Password))
PasswordBox.Password = string.Empty;
}
private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
{
if (DataContext is AdminLoginViewModel vm)
vm.Password = PasswordBox.Password;
}
private void LogoImage_OnImageFailed(object sender, ExceptionRoutedEventArgs e)
{
// If assets/logo.png isn't present in output, fall back to text title.
LogoImage.Visibility = Visibility.Collapsed;
LogoFallbackText.Visibility = Visibility.Visible;
}
private void TryLoadLogo()
{
try
{
var uri = new Uri("pack://siteoforigin:,,,/assets/logo4.png", UriKind.Absolute);
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = uri;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
LogoImage.Source = bmp;
LogoFallbackText.Visibility = Visibility.Collapsed;
LogoImage.Visibility = Visibility.Visible;
}
catch
{
LogoImage.Visibility = Visibility.Collapsed;
LogoFallbackText.Visibility = Visibility.Visible;
}
}
private void AdminLogin_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter)
return;
if (DataContext is AdminLoginViewModel vm && vm.AdminLoginCommand.CanExecute(null))
{
vm.AdminLoginCommand.Execute(null);
e.Handled = true;
}
}
}