using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using LehrerApp.Desktop.ViewModels.Groups; using System.ComponentModel; using System.Globalization; namespace LehrerApp.Desktop.Views.Groups; public partial class ExamGradingDialog : Window { private static readonly IBrush InvalidBackground = new SolidColorBrush(Color.Parse("#FFCDD2")); private const string PointsCellName = "Pts"; private const string CommentCellName = "Comment"; /// Aufgaben-Spalten in Aufgabenreihenfolge — nicht über einen festen Index-Offset in /// grid.Columns auflösen, weil bei A/B-Arbeiten noch die "Fassung"-Spalte davor steht. private readonly List _taskColumns = []; public ExamGradingDialog() { InitializeComponent(); // Tunnel statt KeyDown am TextBox: so kommt die Navigation vor TextBox und DataGrid an // die Reihe. Vorher hat die DataGrid-eigene Tastenbehandlung Enter/Pfeile teilweise selbst // ausgewertet (Sprung in die erste Zeile, Zellauswahl ohne offenes Eingabefeld). AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); } private DataGrid? Grid => this.FindControl("ResultGrid"); protected override void OnOpened(EventArgs e) { base.OnOpened(e); if (DataContext is not ExamGradingDialogViewModel vm || Grid is not { } grid) return; BuildColumns(vm, grid); grid.CurrentCellChanged += (_, _) => OnGridCurrentCellChanged(vm, grid); if (vm.FirstCell() is { } first) FocusPointsCell(vm, first.Row, first.Task); } private void BuildColumns(ExamGradingDialogViewModel vm, DataGrid grid) { grid.Columns.Clear(); _taskColumns.Clear(); grid.Columns.Add(new DataGridTextColumn { Header = "Schüler", Binding = new Binding("Name"), IsReadOnly = true, Width = new DataGridLength(170, DataGridLengthUnitType.Pixel), }); if (vm.HasVariants) grid.Columns.Add(new DataGridTemplateColumn { Header = "Fassung", Width = new DataGridLength(82, DataGridLengthUnitType.Pixel), CellTemplate = new FuncDataTemplate((_, _) => { var choice = new ComboBox(); choice.Bind(ItemsControl.ItemsSourceProperty, new Binding(nameof(ExamResultRow.VariantOptions))); choice.Bind(SelectingItemsControl.SelectedItemProperty, new Binding(nameof(ExamResultRow.VariantName)) { Mode = BindingMode.TwoWay }); return choice; }), }); for (var i = 0; i < vm.Tasks.Count; i++) { var column = new DataGridTemplateColumn { Header = vm.TaskHeaders[i], Width = new DataGridLength(1, DataGridLengthUnitType.Star), CellTemplate = BuildPointsCellTemplate(i), }; _taskColumns.Add(column); grid.Columns.Add(column); } grid.Columns.Add(new DataGridTextColumn { Header = "Summe", Binding = new Binding("TotalPointsDisplay"), IsReadOnly = true, Width = new DataGridLength(70, DataGridLengthUnitType.Pixel), }); grid.Columns.Add(new DataGridTextColumn { Header = "Note", Binding = new Binding("GradeDisplay"), IsReadOnly = true, Width = new DataGridLength(70, DataGridLengthUnitType.Pixel), }); grid.Columns.Add(new DataGridTemplateColumn { Header = "Abw.", Width = new DataGridLength(50, DataGridLengthUnitType.Pixel), CellTemplate = new FuncDataTemplate((_, _) => { var cb = new CheckBox { HorizontalAlignment = HorizontalAlignment.Center }; cb.Bind(ToggleButton.IsCheckedProperty, new Binding(nameof(ExamResultRow.Absent)) { Mode = BindingMode.TwoWay }); return cb; }), }); grid.Columns.Add(new DataGridTemplateColumn { Header = "Kommentar", Width = new DataGridLength(180, DataGridLengthUnitType.Pixel), CellTemplate = new FuncDataTemplate((_, _) => { var tb = new TextBox { Name = CommentCellName, BorderThickness = new Thickness(0), Background = Brushes.Transparent, Padding = new Thickness(6, 4), }; tb.Bind(TextBox.TextProperty, new Binding(nameof(ExamResultRow.Comment)) { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.LostFocus }); return tb; }), }); } /// Die Zelle hängt sich bei jedem DataContext-Wechsel neu an die passende PointsCell, statt /// die Zeile beim Erzeugen im Closure festzuhalten: Das DataGrid recycelt Zeilen beim /// Scrollen, ein festgehaltener Verweis würde dann Punkte in die Zeile eines anderen /// Schülers schreiben. private static IDataTemplate BuildPointsCellTemplate(int taskIndex) { return new FuncDataTemplate((_, _) => { var tb = new TextBox { Name = PointsCellName, Tag = taskIndex, BorderThickness = new Thickness(0), Background = Brushes.Transparent, Padding = new Thickness(6, 4), HorizontalContentAlignment = HorizontalAlignment.Center, }; PointsCell? cell = null; void OnCellPropertyChanged(object? _, PropertyChangedEventArgs pe) { if (cell is null) return; if (pe.PropertyName == nameof(PointsCell.IsInvalid)) UpdateInvalidVisual(tb, cell.IsInvalid); if (pe.PropertyName == nameof(PointsCell.IsApplicable)) tb.IsEnabled = cell.IsApplicable; } tb.DataContextChanged += (_, _) => { if (cell is not null) cell.PropertyChanged -= OnCellPropertyChanged; cell = (tb.DataContext as ExamResultRow)?.Cells.ElementAtOrDefault(taskIndex); if (cell is null) { tb.Text = ""; tb.IsEnabled = false; return; } cell.PropertyChanged += OnCellPropertyChanged; tb.Text = FormatPoints(cell.Value); tb.IsEnabled = cell.IsApplicable; ToolTip.SetTip(tb, $"max. {FormatPoints(cell.MaxPoints)} Punkte"); UpdateInvalidVisual(tb, cell.IsInvalid); }; tb.LostFocus += (_, _) => { if (cell is not null) CommitPointsCell(tb, cell); }; return tb; }); } private static void CommitPointsCell(TextBox tb, PointsCell cell) { var text = tb.Text?.Trim().Replace(',', '.'); double? parsed = string.IsNullOrEmpty(text) ? null : double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var v) ? v : cell.Value; cell.TrySetValue(parsed); tb.Text = FormatPoints(cell.Value); } private static void UpdateInvalidVisual(TextBox tb, bool invalid) => tb.Background = invalid ? InvalidBackground : Brushes.Transparent; private static string FormatPoints(double? value) => value?.ToString("0.##", CultureInfo.InvariantCulture) ?? ""; /// Zwei Korrektur-Workflows (Nutzer-Feedback), umschaltbar oben im Dialog: "Schüler für /// Schüler" (Enter läuft die Zeile entlang, am Ende weiter zur nächsten Arbeit) und "Aufgabe /// für Aufgabe" (Enter läuft die Spalte hinunter, am Ende weiter zur nächsten Aufgabe). /// Umschalt+Enter geht in derselben Reihenfolge zurück. Pfeiltasten bewegen sich unabhängig /// vom Modus direkt in ihre Richtung — links/rechts nur, wenn der Cursor am Rand steht oder /// alles markiert ist, damit man innerhalb einer Zahl noch korrigieren kann. private void OnPreviewKeyDown(object? sender, KeyEventArgs e) { if (DataContext is not ExamGradingDialogViewModel vm) return; if ((e.Source as Visual)?.FindAncestorOfType(includeSelf: true) is not { } tb) return; if (tb.DataContext is not ExamResultRow row) return; var rowIdx = vm.Rows.IndexOf(row); if (rowIdx < 0) return; if (tb.Name == PointsCellName && tb.Tag is int taskIdx) { if (ToMove(e, tb) is not { } move) return; e.Handled = true; if (vm.NextCell(rowIdx, taskIdx, move) is { } target) FocusPointsCell(vm, target.Row, target.Task); } else if (tb.Name == CommentCellName && e.Key is Key.Down or Key.Up or Key.Enter) { e.Handled = true; var targetIdx = e.Key == Key.Up || e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? rowIdx - 1 : rowIdx + 1; if (targetIdx < 0 || targetIdx >= vm.Rows.Count || Grid is not { } grid) return; FocusCell(grid, vm.Rows[targetIdx], grid.Columns[^1], t => t.Name == CommentCellName); } } private static GradingMove? ToMove(KeyEventArgs e, TextBox tb) { var len = tb.Text?.Length ?? 0; var selStart = Math.Min(tb.SelectionStart, tb.SelectionEnd); var selEnd = Math.Max(tb.SelectionStart, tb.SelectionEnd); var allSelected = selStart == 0 && selEnd == len; var noSelection = selStart == selEnd; return e.Key switch { Key.Enter when e.KeyModifiers.HasFlag(KeyModifiers.Shift) => GradingMove.Previous, Key.Enter => GradingMove.Next, Key.Up => GradingMove.Up, Key.Down => GradingMove.Down, Key.Left when allSelected || (noSelection && tb.CaretIndex == 0) => GradingMove.Left, Key.Right when allSelected || (noSelection && tb.CaretIndex == len) => GradingMove.Right, _ => null, }; } /// Navigiert das DataGrid selbst (z. B. nach Klick auf den Schülernamen per Pfeiltaste) in /// eine Aufgabenzelle, wird deren Eingabefeld direkt geöffnet, statt nur die Zelle zu markieren. private void OnGridCurrentCellChanged(ExamGradingDialogViewModel vm, DataGrid grid) { if (FocusManager?.GetFocusedElement() is TextBox) return; var taskIdx = grid.CurrentColumn is { } col ? _taskColumns.IndexOf(col) : -1; if (taskIdx < 0 || grid.SelectedItem is not ExamResultRow row) return; var rowIdx = vm.Rows.IndexOf(row); if (vm.IsEditable(rowIdx, taskIdx)) FocusPointsCell(vm, rowIdx, taskIdx); } private void FocusPointsCell(ExamGradingDialogViewModel vm, int rowIdx, int taskIdx) { if (Grid is not { } grid || taskIdx >= _taskColumns.Count) return; FocusCell(grid, vm.Rows[rowIdx], _taskColumns[taskIdx], t => t.Name == PointsCellName && t.Tag is int i && i == taskIdx); } /// Erst scrollen (auch horizontal), dann nach dem Layout-Durchlauf das TextBox-Element der /// Zielzelle suchen — vorher existiert es bei virtualisierten Zeilen eventuell noch nicht. private static void FocusCell(DataGrid grid, object rowItem, DataGridColumn column, Func match) { grid.ScrollIntoView(rowItem, column); Dispatcher.UIThread.Post(() => { var target = grid.GetVisualDescendants().OfType() .FirstOrDefault(t => t.DataContext == rowItem && t.IsEffectivelyVisible && match(t)); if (target is null) return; target.Focus(NavigationMethod.Tab); target.SelectAll(); }, DispatcherPriority.Loaded); } private void OnClose(object? sender, RoutedEventArgs e) => Close(); }