How to add an item at specific index in a specific group?
In SfListView, you can add an item at specific index in a specific group by using KeySelector property and Key value of each group. Since, each group is identified by its Key which holds the underlying data related to the group. When a new item is added at runtime, you need to find that which group does the item belongs to by using PropertyInfoCollection, PropertyName and KeySelector and after getting the desired group’s GroupResult value, insert the particular item into a specified index and please follow the below steps to achieve this.
To add a new data into the underlying collection, please refer the following code example,
var contact = new Contacts(); contact.ContactName = "Adam"; contact.ContactNumber = "783-457-567"; contact.DisplayString = "A"; contact.ContactImage = ImageSource.FromResource("Grouping.Images.Image" + 25 + ".png"); //Adding data into underlying collection ViewModel.ContactItems.Add(contact);
You can determine that which group does the newly added item belongs to by using KeySelector property and Key value of the group by passing the underlying data into the parameter in the below method.
internal void GetGroupResult(object ItemData) { var descriptor = listView.DataSource.GroupDescriptors[0]; object key; if (descriptor.KeySelector == null) { var propertyInfoCollection = new PropertyInfoCollection(ItemData.GetType()); key = propertyInfoCollection.GetValue(ItemData, descriptor.PropertyName); } else key = descriptor.KeySelector(ItemData); itemGroup = this.listView.DataSource.Groups.FirstOrDefault(x => x.Key == key); descriptor = null; key = null; }
To add the data into the specific group at the specific index refer the below code example,
internal void InsertItemInGroup(List<object> items, object Item, int InsertAt) { var visualContainer = listView.GetType().GetRuntimeProperties().First(p => p.Name == "VisualContainer").GetValue(listView) as VisualContainer; items.Remove(Item); items.Insert(InsertAt, Item); visualContainer.ForceLayout(); }
Now run the application to render the following output.
Sample Link: ListView_Grouping