using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using Chronos.App.Jobs; namespace Chronos.App.Sections; public partial class JobsView : UserControl { private JobsViewModel? _model; private IInputElement? _beforeDialog; public JobsView() { InitializeComponent(); DataContextChanged += OnDataContextChanged; } /// Loads older history when the list scrolls near its end. private void OnScrollChanged(object sender, ScrollChangedEventArgs e) { if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return; if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync(); } private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (_model is not null) { _model.RowRevealRequested -= OnRevealRequested; _model.Schedules.PropertyChanged -= OnSchedulesChanged; } _model = e.NewValue as JobsViewModel; if (_model is not null) { _model.RowRevealRequested += OnRevealRequested; _model.Schedules.PropertyChanged += OnSchedulesChanged; } } /// A job shown from Jobs › Scheduled: its row comes into view (the list is visible again by then) and takes the keyboard. private void OnRevealRequested(JobRowViewModel row) => Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => { JobList.ScrollIntoView(row); JobList.UpdateLayout(); if (JobList.ItemContainerGenerator.ContainerFromItem(row) is ListBoxItem item) item.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); }); /// /// The schedule editor takes the keyboard when it opens (its first field); when it closes, the keyboard goes back to the /// control that opened it while that can still take it. /// private void OnSchedulesChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != nameof(SchedulesViewModel.Editor) || _model is not { } model) return; if (model.Schedules.Editor is not null) { if (!IsVisible) return; _beforeDialog ??= Keyboard.FocusedElement is Visual focused && IsAncestorOf(focused) ? Keyboard.FocusedElement : null; Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First))); return; } var back = _beforeDialog; _beforeDialog = null; if (!IsVisible) return; Dispatcher.BeginInvoke(DispatcherPriority.Input, () => { if (back is UIElement { IsVisible: true, IsEnabled: true, Focusable: true } element) element.Focus(); }); } }