diff --git a/demo/Ursa.Demo/Pages/TagInputDemo.axaml b/demo/Ursa.Demo/Pages/TagInputDemo.axaml index 8a4f839..822f316 100644 --- a/demo/Ursa.Demo/Pages/TagInputDemo.axaml +++ b/demo/Ursa.Demo/Pages/TagInputDemo.axaml @@ -12,7 +12,9 @@ + AllowDuplicates="False" + Separator="-" + Tags="{Binding Tags}" /> _Tags ; + public ObservableCollection Tags + { + get { return _Tags; } + set { SetProperty(ref _Tags, value); } + } } \ No newline at end of file diff --git a/src/Ursa/Controls/TagInput/TagInput.cs b/src/Ursa/Controls/TagInput/TagInput.cs index f0f0c69..f57e7eb 100644 --- a/src/Ursa/Controls/TagInput/TagInput.cs +++ b/src/Ursa/Controls/TagInput/TagInput.cs @@ -49,8 +49,11 @@ public class TagInput : TemplatedControl public TagInput() { _textBox = new TextBox(); - _textBox.AddHandler(InputElement.KeyDownEvent, OnTextBoxKeyDown, RoutingStrategies.Tunnel); - Items = new AvaloniaList(); + _textBox.AddHandler(KeyDownEvent, OnTextBoxKeyDown, RoutingStrategies.Tunnel); + Items = new AvaloniaList + { + _textBox + }; Tags = new ObservableCollection(); } @@ -123,7 +126,6 @@ public class TagInput : TemplatedControl { base.OnApplyTemplate(e); _itemsControl = e.NameScope.Find(PART_ItemsControl); - Items.Add(_textBox); } private void OnInputThemePropertyChanged(AvaloniaPropertyChangedEventArgs args) @@ -143,12 +145,13 @@ public class TagInput : TemplatedControl { Items.RemoveAt(Items.Count - 1); } - - for (int i = 0; i < newTags.Count; i++) + if (newTags != null) { - Items.Insert(Items.Count - 1, newTags[i]); - } - + for (int i = 0; i < newTags.Count; i++) + { + Items.Insert(Items.Count - 1, newTags[i]); + } + } if (oldTags is INotifyCollectionChanged inccold) { inccold.CollectionChanged-= OnCollectionChanged; @@ -207,24 +210,22 @@ public class TagInput : TemplatedControl values = new[] { _textBox.Text }; } - if (!AllowDuplicates) - { + if (!AllowDuplicates && Tags != null) values = values.Distinct().Except(Tags).ToArray(); - } for (int i = 0; i < values.Length; i++) { int index = Items.Count - 1; // Items.Insert(index, values[i]); - Tags.Insert(index, values[i]); + Tags?.Insert(index, values[i]); } _textBox.Text = ""; } } else if (args.Key == Key.Delete || args.Key == Key.Back) - { - if (_textBox.Text?.Length == 0) + { + if (string.IsNullOrEmpty(_textBox.Text)||_textBox.Text?.Length == 0) { if (Tags.Count == 0) {