diff --git a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs index 188685f796..c8c15bc079 100644 --- a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs +++ b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs @@ -333,6 +333,11 @@ namespace Avalonia.Controls.Primitives case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Reset: SelectedIndex = IndexOf(Items, SelectedItem); + + if (AlwaysSelected && SelectedIndex == -1 && ItemCount > 0) + { + SelectedIndex = 0; + } break; } } diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs index 8618387150..72f2b8022f 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs @@ -1,6 +1,8 @@ // Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. +using System.Collections.Generic; +using System.Collections.Specialized; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; @@ -43,6 +45,24 @@ namespace Avalonia.Controls.UnitTests.Primitives Assert.Equal("foo", target.SelectedItem); } + + [Fact] + public void First_Item_Should_Be_Selected_When_Reset() + { + var items = new ResetOnAdd(); + var target = new TestSelector + { + Items = items, + Template = Template(), + }; + + target.ApplyTemplate(); + items.Add("foo"); + + Assert.Equal(0, target.SelectedIndex); + Assert.Equal("foo", target.SelectedItem); + } + [Fact] public void Item_Should_Be_Selected_When_Selection_Removed() { @@ -100,5 +120,18 @@ namespace Avalonia.Controls.UnitTests.Primitives SelectionModeProperty.OverrideDefaultValue(SelectionMode.AlwaysSelected); } } + + private class ResetOnAdd : List, INotifyCollectionChanged + { + public event NotifyCollectionChangedEventHandler CollectionChanged; + + public new void Add(string item) + { + base.Add(item); + CollectionChanged?.Invoke( + this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + } + } } }