feat: add key down handling to MultiAutoCompleteBox for item removal on empty text

This commit is contained in:
rabbitism
2025-09-14 22:09:48 +08:00
parent 609607f68a
commit ab8927d261

View File

@@ -16,6 +16,7 @@ using Avalonia.Threading;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using Irihi.Avalonia.Shared.Contracts; using Irihi.Avalonia.Shared.Contracts;
using Irihi.Avalonia.Shared.Helpers; using Irihi.Avalonia.Shared.Helpers;
using Irihi.Avalonia.Shared.Reactive;
using Ursa.Common; using Ursa.Common;
@@ -150,6 +151,7 @@ public partial class MultiAutoCompleteBox : TemplatedControl, IInnerContentContr
private TextBox? _textBox; private TextBox? _textBox;
private IDisposable? _textBoxSubscriptions; private IDisposable? _textBoxSubscriptions;
private IDisposable? _textBoxKeyDownSubscriptions;
/// <summary> /// <summary>
/// Gets or sets the last observed text box selection start location. /// Gets or sets the last observed text box selection start location.
@@ -216,6 +218,7 @@ public partial class MultiAutoCompleteBox : TemplatedControl, IInnerContentContr
set set
{ {
_textBoxSubscriptions?.Dispose(); _textBoxSubscriptions?.Dispose();
_textBoxKeyDownSubscriptions?.Dispose();
_textBox = value; _textBox = value;
// Attach handlers // Attach handlers
@@ -225,12 +228,24 @@ public partial class MultiAutoCompleteBox : TemplatedControl, IInnerContentContr
_textBox.GetObservable(TextBox.TextProperty) _textBox.GetObservable(TextBox.TextProperty)
.Skip(1) .Skip(1)
.Subscribe(_ => OnTextBoxTextChanged()); .Subscribe(_ => OnTextBoxTextChanged());
_textBoxKeyDownSubscriptions =
_textBox.AddDisposableHandler(KeyDownEvent, OnTextBoxKeyDown, RoutingStrategies.Tunnel);
if (Text != null) UpdateTextValue(Text); if (Text != null) UpdateTextValue(Text);
} }
} }
} }
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.Key == Key.Back || e.Key == Key.Delete )&& string.IsNullOrEmpty(TextBox?.Text) )
{
if (SelectedItems?.Count > 0)
{
SelectedItems.RemoveAt(SelectedItems.Count - 1);
}
}
}
private int TextBoxSelectionStart private int TextBoxSelectionStart
{ {
get get
@@ -1642,6 +1657,7 @@ public partial class MultiAutoCompleteBox : TemplatedControl, IInnerContentContr
// Completion will update the selected value // Completion will update the selected value
//UpdateTextCompletion(false); //UpdateTextCompletion(false);
UpdateTextValue(string.Empty, false);
// Text should not be selected // Text should not be selected
ClearTextBoxSelection(); ClearTextBoxSelection();