Browse Source

Merge pull request #2771 from AvaloniaUI/fixes/2754-always-select-on-reset

Make SelectingItemsControl.AlwaysSelect work with Reset.
pull/2785/head
Nikita Tsukanov 7 years ago
committed by GitHub
parent
commit
8b35465a5f
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      src/Avalonia.Controls/Primitives/SelectingItemsControl.cs
  2. 33
      tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs

5
src/Avalonia.Controls/Primitives/SelectingItemsControl.cs

@ -333,6 +333,11 @@ namespace Avalonia.Controls.Primitives
case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Reset: case NotifyCollectionChangedAction.Reset:
SelectedIndex = IndexOf(Items, SelectedItem); SelectedIndex = IndexOf(Items, SelectedItem);
if (AlwaysSelected && SelectedIndex == -1 && ItemCount > 0)
{
SelectedIndex = 0;
}
break; break;
} }
} }

33
tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_AutoSelect.cs

@ -1,6 +1,8 @@
// Copyright (c) The Avalonia Project. All rights reserved. // 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. // 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.Collections;
using Avalonia.Controls.Presenters; using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives;
@ -43,6 +45,24 @@ namespace Avalonia.Controls.UnitTests.Primitives
Assert.Equal("foo", target.SelectedItem); 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] [Fact]
public void Item_Should_Be_Selected_When_Selection_Removed() public void Item_Should_Be_Selected_When_Selection_Removed()
{ {
@ -100,5 +120,18 @@ namespace Avalonia.Controls.UnitTests.Primitives
SelectionModeProperty.OverrideDefaultValue<TestSelector>(SelectionMode.AlwaysSelected); SelectionModeProperty.OverrideDefaultValue<TestSelector>(SelectionMode.AlwaysSelected);
} }
} }
private class ResetOnAdd : List<string>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public new void Add(string item)
{
base.Add(item);
CollectionChanged?.Invoke(
this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
} }
} }

Loading…
Cancel
Save