using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using Avalonia.Layout; namespace OpenNest.Avalonia.Controls { /// /// A text box with a list to pick from, as a WinForms drop-down combo box: any text can be /// typed, typing offers the items that start with it, and the arrow button lists them all. /// internal sealed class EditableCombo : UserControl { private readonly AutoCompleteBox box = new() { FilterMode = AutoCompleteFilterMode.StartsWith, MinimumPrefixLength = 1, MaxDropDownHeight = 320, HorizontalAlignment = HorizontalAlignment.Stretch, }; private IReadOnlyList items = Array.Empty(); public EditableCombo() { var open = new Button { Content = "▾", Padding = new global::Avalonia.Thickness(6, 0), VerticalAlignment = VerticalAlignment.Stretch, Focusable = false, }; open.Click += (_, _) => ShowAll(); box.DropDownClosed += (_, _) => box.FilterMode = AutoCompleteFilterMode.StartsWith; box.TextChanged += (_, _) => TextChanged?.Invoke(this, EventArgs.Empty); box.LostFocus += (_, _) => LostFocusText?.Invoke(this, EventArgs.Empty); var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; grid.Children.Add(box); Grid.SetColumn(open, 1); grid.Children.Add(open); Content = grid; } /// Raised when the text changes, typed or picked. public event EventHandler TextChanged; /// Raised when the box loses the keyboard, for tidying the typed text. public event EventHandler LostFocusText; public string Text { get => box.Text ?? ""; set => box.Text = value ?? ""; } /// The items listed, in order; the text is kept. public IReadOnlyList Items { get => items; set { var text = Text; items = (value ?? Array.Empty()).ToList(); box.ItemsSource = items; if (Text != text) Text = text; } } public bool FocusText() => box.Focus(); // Lists every item, whatever is typed, as a WinForms combo box's arrow does. private void ShowAll() { if (items.Count == 0) return; box.FilterMode = AutoCompleteFilterMode.None; var text = Text; box.ItemsSource = null; box.ItemsSource = items; if (Text != text) Text = text; box.IsDropDownOpen = true; } } }