How to hide the empty rows of a list view in xamarin.forms
So, the solution I found is to force listview layout every time you add/remove an item. You also need to wrap the list in stacklayout.
<StackLayout BackgroundColor="LightGray">
<Label Text="Liquit Zones" TextColor="Gray" FontSize="Small" Margin="10"/>
<StackLayout>
<ListView x:Name="ItemsListView" SeparatorColor="LightGray" BackgroundColor="Green" RowHeight="60" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="AddItemClicked" Text="Add" />
<MenuItem Clicked="RemoveItemClicked" CommandParameter="{Binding .}" Text="Trash" IsDestructive="True" />
</ViewCell.ContextActions>
<StackLayout Padding="15, 5, 0, 0" Orientation="Horizontal" BackgroundColor="White">
<Image Source="{Binding Image}" HorizontalOptions="Start"/>
<StackLayout Orientation="Vertical">
<Label Text = "{Binding ItemText}" FontSize="20" TextColor="Black" />
<Label Text = "{Binding ItemDetail}" TextColor="LightGray" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Footer>
<Label />
</ListView.Footer>
</ListView>
</StackLayout>
<Button Text="Add Item" TextColor="Black" HorizontalOptions="FillAndExpand" FontSize="Medium" Clicked="AddItemClicked" BackgroundColor="White"/>
</StackLayout>
Because you know your cell height you can do this:
void AddItemClicked(object sender, EventArgs e)
{
SampleData data = new SampleData();
data.ItemText = "An Item";
data.ItemDetail = "Item - " + (itemsListCollection.Count + 1).ToString();
itemsListCollection.Add(data);
ItemsListView.HeightRequest = itemsListCollection.Count * 60;
//ForceLayout();
}
void RemoveItemClicked(object sender, EventArgs e)
{
SampleData item =(SampleData)((MenuItem)sender).CommandParameter;
if (item != null)
{
itemsListCollection.Remove(item);
}
ItemsListView.HeightRequest = itemsListCollection.Count * 60;
}
class SampleData:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string itemText;
public string ItemText
{
get
{
return itemText;
}
set
{
itemText = value;
NotifyPropertyChanged("ItemText");
}
}
private string itemDetail;
public string ItemDetail
{
get
{
return itemDetail;
}
set
{
itemDetail = value;
NotifyPropertyChanged("ItemDetail");
}
}
private void NotifyPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
An easy way to remove the empty rows of a ListView is to set an empty footer for the ListView.
ListView HeaderList = new ListView()
{
Footer = ""
};
or in XAML
<ListView x:Name="HeaderList" Footer=""></ListView>