Reputation: 121
How can i add new item to grouped Listview? Should i regroup my items and assign it to Listview.ItemsSource everytime? I added button to update observable collection which is bound to the Grouped ListView. Is it the only one correct way to update ListView? Where am i wrong? Model class:
public class Phone
{
public string Title { get; set; }
public string Company { get; set; }
public int Price { get; set; }
}
MainPage
public partial class MainPage : ContentPage
{
// список групп, к которым идет привязка
public ObservableCollection<Grouping<string, Phone>> PhoneGroups { get; set; }
public MainPage()
{
InitializeComponent();
// начальные данные
var phones = new List<Phone>
{
new Phone {Title="Galaxy S8", Company="Samsung", Price=60000 },
new Phone {Title="Galaxy S7 Edge", Company="Samsung", Price=50000 },
new Phone {Title="Huawei P10", Company="Huawei", Price=10000 },
new Phone {Title="Huawe Mate 8", Company="Huawei", Price=29000 },
new Phone {Title="Mi6", Company="Xiaomi", Price=55000 },
new Phone {Title="iPhone 7", Company="Apple", Price=38000 },
new Phone {Title="iPhone 6S", Company="Apple", Price=50000 }
};
// получаем группы
var groups = phones.GroupBy(p => p.Company).Select(g => new Grouping<string, Phone>(g.Key, g));
// передаем группы в PhoneGroups
PhoneGroups = new ObservableCollection<Grouping<string, Phone>>(groups);
phonesList.ItemsSource = PhoneGroups;
}
private void AddItemButton_Clicked(object sender, EventArgs e)
{
phones.Add
(
new Phone { Title = "Galaxy S3", Company = "Samsung", Price = 2500 }
);
// получаем группы
var groups = phones.GroupBy(p => p.Company).Select(g => new Grouping<string, Phone>(g.Key, g));
// передаем группы в PhoneGroups
PhoneGroups = new ObservableCollection<Grouping<string, Phone>>(groups);
phonesList.ItemsSource = PhoneGroups;
}
}
Xaml MainPage
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:HelloApp;assembly=HelloApp"
x:Class="HelloApp.MainPage">
<StackLayout>
<ListView x:Name="phonesList"
HasUnevenRows="True"
GroupDisplayBinding="{Binding Name}"
ItemsSource="{Binding PhoneGroups}"
IsGroupingEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Title}" />
<Label Text="{Binding Price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button x:Name="AddItemButton" Clicked="AddItemButton_Clicked" Text="AddItem" />
</StackLayout>
</ContentPage>
Upvotes: 2
Views: 770
Reputation: 93
An Observable collection listens to changes when an item is removed or added or modified. One simple way will be:
var group=phonegroup[indexOfTheGroup];
group.Phone.add(new Phone{});
phonegroup[indexOfTheGroup]=group;
Cheers. This Worked for me.
Upvotes: 1