Skip to content

Commit

Permalink
Fix empty view not removed when adding an item on an empty observable…
Browse files Browse the repository at this point in the history
… collection
  • Loading branch information
albyrock87 committed Aug 18, 2024
1 parent b366f0d commit 997079d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Controls/src/Core/BindableLayout/BindableLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,16 @@ void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArg
}

e.Apply(
insert: (item, index, _) => layout.Insert(CreateItemView(item, SelectTemplate(item, layout)), index),
insert: (item, index, _) =>
{
var layoutChildren = layout.Children;
if (layoutChildren.Count == 1 && layoutChildren[0] == _currentEmptyView)
{
layout.RemoveAt(0);
}

layout.Insert(CreateItemView(item, SelectTemplate(item, layout)), index);
},
removeAt: (item, index) =>
{
var child = (View)layout.Children[index]!;
Expand Down
41 changes: 41 additions & 0 deletions src/Controls/tests/Core.UnitTests/BindableLayoutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,48 @@ public void WorksWithDuplicateItems()
itemsSource.Remove(0);
Assert.True(IsLayoutWithItemsSource(itemsSource, layout));
}

[Fact]
public void RemovesEmptyViewWhenAddingTheFirstItem()
{
var layout = new StackLayout
{
IsPlatformEnabled = true,
};

var itemsSource = new ObservableCollection<int>();

var emptyView = new Label();
BindableLayout.SetEmptyView(layout, emptyView);

BindableLayout.SetItemsSource(layout, itemsSource);
Assert.Single(layout.Children);
Assert.Equal(emptyView, layout[0]);

itemsSource.Add(0);
Assert.True(IsLayoutWithItemsSource(itemsSource, layout));
}

[Fact]
public void AddsEmptyViewWhenRemovingRemainingItem()
{
var layout = new StackLayout
{
IsPlatformEnabled = true,
};

var itemsSource = new ObservableCollection<int>(Enumerable.Range(0, 1));

var emptyView = new Label();
BindableLayout.SetEmptyView(layout, emptyView);

BindableLayout.SetItemsSource(layout, itemsSource);
Assert.True(IsLayoutWithItemsSource(itemsSource, layout));

itemsSource.RemoveAt(0);
Assert.Single(layout.Children);
Assert.Equal(emptyView, layout[0]);
}

[Fact]
public void ValidateBindableProperties()
Expand Down

0 comments on commit 997079d

Please sign in to comment.