Category / Section
How to create an expandable ListView (SfListView) in .NET MAUI ?
1 min read
The .NET MAUI ListView (SfListView) allows you to expand the items at run time by setting the AutoFitMode property to DynamicHeight. Based on the Model property, you can show or hide additional views in the ItemTemplate.
XAML
<ListView:SfListView x:Name="listView" ItemsSource="{Binding ContactsInfo}" AutoFitMode="DynamicHeight" SelectionMode="None" ItemSpacing="0,2.5,0,2.5"> <ListView:SfListView.ItemTemplate> <DataTemplate> <Grid x:Name="grid" VerticalOptions="FillAndExpand" BackgroundColor="White" HorizontalOptions="FillAndExpand" RowSpacing="0"> <Grid.RowDefinitions> <RowDefinition Height="60" /> <RowDefinition Height ="*"/> </Grid.RowDefinitions> <Grid RowSpacing="0"> ... </Grid> <!--Expandable view--> <Grid x:Name="ExpandGrid" IsVisible="{Binding IsVisible}" ColumnSpacing="0" RowSpacing="0" Grid.Row="1" Padding="10,0,0,0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"> ... </Grid> </Grid> </DataTemplate> </ListView:SfListView.ItemTemplate> </ListView:SfListView>
C#
In the SfListView.ItemTapped event, update the IsVisible property. For the MacCatalyst platform, refresh the item by using the SfListView.RefreshItem method.
private void ListView_ItemTapped(object sender, Syncfusion.Maui.ListView.ItemTappedEventArgs e) { if (tappedItem != null && tappedItem.IsVisible) { var previousIndex = listview.DataSource.DisplayItems.IndexOf(tappedItem); tappedItem.IsVisible = false; if (Device.RuntimePlatform != Device.MacCatalyst) Device.BeginInvokeOnMainThread(() => { listview.RefreshItem(previousIndex, previousIndex, false); }); } if (tappedItem == (e.ItemData as Contact)) { if (Device.RuntimePlatform == Device.MacCatalyst) { var previousIndex = listview.DataSource.DisplayItems.IndexOf(tappedItem); Device.BeginInvokeOnMainThread(() => { listview.RefreshItem(previousIndex, previousIndex, false); }); } tappedItem = null; return; } tappedItem = e.ItemData as Contact; tappedItem.IsVisible = true; if (Device.RuntimePlatform == Device.MacCatalyst) { var visibleLines = this.listview.GetVisualContainer().ScrollRows.GetVisibleLines(); var firstIndex = visibleLines[visibleLines.FirstBodyVisibleIndex].LineIndex; var lastIndex = visibleLines[visibleLines.LastBodyVisibleIndex].LineIndex; Device.BeginInvokeOnMainThread(() => { listview.RefreshItem(firstIndex, lastIndex, false); }); } else { var currentIndex = listview.DataSource.DisplayItems.IndexOf(e.ItemData); Device.BeginInvokeOnMainThread(() => { listview.RefreshItem(currentIndex, currentIndex, false); }); } }
Take a moment to peruse the documentation, to learn more about item size customization in SfListView with code.