Browse Source

Update SelectedIndex when items removed before selection.

pull/2673/head
Steven Kirk 7 years ago
parent
commit
ca23d03f98
  1. 14
      src/Avalonia.Controls/Primitives/SelectingItemsControl.cs
  2. 26
      tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs
  3. 28
      tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_Multiple.cs

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

@ -316,26 +316,22 @@ namespace Avalonia.Controls.Primitives
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
var selectedIndex = SelectedIndex;
if (selectedIndex >= e.OldStartingIndex &&
selectedIndex < e.OldStartingIndex + e.OldItems.Count)
if (SelectedIndex >= e.OldStartingIndex && SelectedIndex < e.OldStartingIndex + e.OldItems.Count)
{
if (!AlwaysSelected)
{
selectedIndex = SelectedIndex = -1;
SelectedIndex = -1;
}
else
{
LostSelection();
}
}
var items = Items?.Cast<object>();
if (selectedIndex >= items.Count())
else if (e.OldStartingIndex <= SelectedIndex)
{
selectedIndex = SelectedIndex = items.Count() - 1;
UpdateSelectedItem(SelectedIndex - e.OldItems.Count, false);
}
break;
case NotifyCollectionChangedAction.Move:

26
tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs

@ -842,6 +842,32 @@ namespace Avalonia.Controls.UnitTests.Primitives
Assert.Equal("Bar", target.SelectedItem);
}
[Fact]
public void Removing_Item_Before_SelectedItem_Should_Update_SelectedIndex()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
SelectedIndex = 1,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
items.RemoveAt(0);
Assert.Equal(0, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
}
private FuncControlTemplate Template()
{
return new FuncControlTemplate<SelectingItemsControl>(control =>

28
tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_Multiple.cs

@ -840,6 +840,34 @@ namespace Avalonia.Controls.UnitTests.Primitives
Assert.Equal(new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" }, target.SelectedItems);
}
[Fact]
public void Adding_Item_Before_SelectedItems_Should_Update_Indexes()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
items.Insert(0, "Qux");
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Foo", target.SelectedItem);
}
private IEnumerable<int> SelectedContainers(SelectingItemsControl target)
{
return target.Presenter.Panel.Children

Loading…
Cancel
Save