Category / Section
How to add a new group to the top of the Xamarin.Forms ListView (SfListView)?
1 min read
The Xamarin.Forms SfListView allows you to reorder the groups added to the top at runtime. By default, it will be added to the last group when a new group is created at runtime.
XAML
Add Button to add a new item to create a new group at run time.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ListViewXamarin" xmlns:syncfusion="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms" x:Class="ListViewXamarin.MainPage"> <ContentPage.BindingContext> <local:ContactsViewModel/> </ContentPage.BindingContext> <ContentPage.Behaviors> <local:Behavior/> </ContentPage.Behaviors> <ContentPage.Content> <StackLayout> <Button Text="Add item" x:Name="addButton" HeightRequest="50"/> <syncfusion:SfListView x:Name="listView" ItemSize="60" ItemsSource="{Binding ContactsInfo}"> <syncfusion:SfListView.ItemTemplate > <DataTemplate> ... </DataTemplate> </syncfusion:SfListView.ItemTemplate> </syncfusion:SfListView> </StackLayout> </ContentPage.Content> </ContentPage>
C#
New data added to the ViewModel collection in the Button.Clicked event that creates a new group. You can move any group to a specific index using the MoveTo method from the Syncfusion.DataSource.Extensions.FunctionalExtensions helper.
By refreshing the view using the SfListView.RefreshView method, you can see the changes in the UI.
public class Behavior : Behavior<ContentPage> { SfListView ListView; Button AddButton; protected override void OnAttachedTo(ContentPage bindable) { ListView = bindable.FindByName<SfListView>("listView"); AddButton = bindable.FindByName<Button>("addButton"); ListView.DataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactName", KeySelector = (object obj1) => { var item = (obj1 as Contacts); return item.ContactName[0].ToString(); } }); AddButton.Clicked += AddButton_Clicked; base.OnAttachedTo(bindable); } private void AddButton_Clicked(object sender, EventArgs e) { var viewModel = (sender as Button).BindingContext as ContactsViewModel; viewModel.ContactsInfo.Add(new Contacts() { ContactName = "John" , ContactImage = ImageSource.FromResource("ListViewXamarin.Images.Image" + 5 + ".png")}); Device.BeginInvokeOnMainThread(() => { var groupCount = ListView.DataSource.Groups.Count; ListView.DataSource.Groups.MoveTo(groupCount - 1, 0); ListView.RefreshView(); }); } }
Output