feat: improve lost focus behavior.

This commit is contained in:
rabbitism
2024-04-23 23:25:59 +08:00
parent 17295c2ddf
commit 46b233c35e
3 changed files with 49 additions and 33 deletions

View File

@@ -21,7 +21,7 @@
<u:TagInput <u:TagInput
Margin="20" Margin="20"
AllowDuplicates="False" AllowDuplicates="False"
CleanLostFocus="true" LostFocusBehavior="Clear"
Separator="-" Separator="-"
Tags="{Binding DistinctTags}" /> Tags="{Binding DistinctTags}" />
<ListBox ItemsSource="{Binding DistinctTags}" /> <ListBox ItemsSource="{Binding DistinctTags}" />

View File

@@ -0,0 +1,8 @@
namespace Ursa.Controls;
public enum LostFocusBehavior
{
None,
Add,
Clear,
}

View File

@@ -60,9 +60,14 @@ public class TagInput : TemplatedControl
private void OnTextBox_LostFocus(object? sender, RoutedEventArgs e) private void OnTextBox_LostFocus(object? sender, RoutedEventArgs e)
{ {
if(CleanLostFocus) switch (LostFocusBehavior)
{ {
case LostFocusBehavior.Add:
AddTags();
break;
case LostFocusBehavior.Clear:
_textBox.Text = ""; _textBox.Text = "";
break;
} }
} }
@@ -95,13 +100,13 @@ public class TagInput : TemplatedControl
set => SetValue(SeparatorProperty, value); set => SetValue(SeparatorProperty, value);
} }
public static readonly StyledProperty<bool> CleanLostFocusProperty = AvaloniaProperty.Register<TagInput, bool>( public static readonly StyledProperty<LostFocusBehavior> LostFocusBehaviorProperty = AvaloniaProperty.Register<TagInput, LostFocusBehavior>(
nameof(CleanLostFocus), defaultValue: false); nameof(LostFocusBehavior));
public bool CleanLostFocus public LostFocusBehavior LostFocusBehavior
{ {
get => GetValue(CleanLostFocusProperty); get => GetValue(LostFocusBehaviorProperty);
set => SetValue(CleanLostFocusProperty, value); set => SetValue(LostFocusBehaviorProperty, value);
} }
@@ -222,8 +227,26 @@ public class TagInput : TemplatedControl
{ {
if (args.Key == Key.Enter) if (args.Key == Key.Enter)
{ {
if (_textBox.Text?.Length > 0) AddTags();
}
else if (args.Key == Key.Delete || args.Key == Key.Back)
{ {
if (string.IsNullOrEmpty(_textBox.Text)||_textBox.Text?.Length == 0)
{
if (Tags.Count == 0)
{
return;
}
int index = Items.Count - 2;
// Items.RemoveAt(index);
Tags.RemoveAt(index);
}
}
}
private void AddTags()
{
if (!(_textBox.Text?.Length > 0)) return;
string[] values; string[] values;
if (!string.IsNullOrEmpty(Separator)) if (!string.IsNullOrEmpty(Separator))
{ {
@@ -247,21 +270,6 @@ public class TagInput : TemplatedControl
_textBox.Text = ""; _textBox.Text = "";
} }
}
else if (args.Key == Key.Delete || args.Key == Key.Back)
{
if (string.IsNullOrEmpty(_textBox.Text)||_textBox.Text?.Length == 0)
{
if (Tags.Count == 0)
{
return;
}
int index = Items.Count - 2;
// Items.RemoveAt(index);
Tags.RemoveAt(index);
}
}
}
public void Close(object o) public void Close(object o)
{ {