98 lines
2.8 KiB
C#
98 lines
2.8 KiB
C#
using System.Text.RegularExpressions;
|
|
using System.Windows;
|
|
using System.Windows.Controls;
|
|
using System.Windows.Input;
|
|
using System.Windows.Media;
|
|
using System.Windows.Threading;
|
|
using UtopiaCanteenSystem.ViewModels;
|
|
|
|
namespace UtopiaCanteenSystem.Views;
|
|
|
|
/// <summary>
|
|
/// Minimal code-behind for focus management and Enter-key submission.
|
|
/// </summary>
|
|
public partial class ScannerDashboardView : UserControl
|
|
{
|
|
private bool _isUnloaded;
|
|
|
|
public ScannerDashboardView()
|
|
{
|
|
InitializeComponent();
|
|
Loaded += OnLoaded;
|
|
Unloaded += OnUnloaded;
|
|
}
|
|
|
|
private void OnLoaded(object sender, RoutedEventArgs e)
|
|
{
|
|
_isUnloaded = false;
|
|
FocusRfidInput(selectAll: true, DispatcherPriority.Input);
|
|
}
|
|
|
|
private void OnUnloaded(object sender, RoutedEventArgs e)
|
|
{
|
|
_isUnloaded = true;
|
|
}
|
|
|
|
private void FocusRfidInput(bool selectAll, DispatcherPriority priority)
|
|
{
|
|
if (_isUnloaded)
|
|
return;
|
|
|
|
Dispatcher.BeginInvoke(() =>
|
|
{
|
|
if (_isUnloaded || !IsVisible || !IsEnabled)
|
|
return;
|
|
|
|
RfidInputTextBox.Focus();
|
|
Keyboard.Focus(RfidInputTextBox);
|
|
|
|
if (selectAll)
|
|
RfidInputTextBox.SelectAll();
|
|
}, priority);
|
|
}
|
|
|
|
private void RfidInputTextBox_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
|
|
{
|
|
// If focus moved into the menu panel (e.g. Site number field), don't steal it back.
|
|
if (IsDescendantOf(MenuPanel, e.NewFocus as DependencyObject))
|
|
return;
|
|
// Otherwise keep view scan-ready (e.g. after closing menu or clicking elsewhere).
|
|
FocusRfidInput(selectAll: false, DispatcherPriority.ApplicationIdle);
|
|
}
|
|
|
|
private static bool IsDescendantOf(DependencyObject? ancestor, DependencyObject? element)
|
|
{
|
|
if (ancestor == null || element == null) return false;
|
|
while (element != null)
|
|
{
|
|
if (element == ancestor) return true;
|
|
element = VisualTreeHelper.GetParent(element);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void RfidInputTextBox_OnKeyDown(object sender, KeyEventArgs e)
|
|
{
|
|
if (e.Key != Key.Enter)
|
|
return;
|
|
|
|
if (DataContext is ScannerDashboardViewModel vm && vm.ScanCommand.CanExecute(null))
|
|
{
|
|
vm.ScanCommand.Execute(null);
|
|
e.Handled = true;
|
|
}
|
|
}
|
|
|
|
private void SiteNumberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
|
|
{
|
|
e.Handled = !Regex.IsMatch(e.Text, @"^\d+$");
|
|
}
|
|
|
|
private void MenuToggleButton_Unchecked(object sender, RoutedEventArgs e)
|
|
{
|
|
// When user closes the menu, focus scanner input so they can scan without clicking it.
|
|
FocusRfidInput(selectAll: false, DispatcherPriority.ApplicationIdle);
|
|
}
|
|
}
|
|
|