Home > Back-end >  ListView ItemSource ObservableRangeCollection<> accessing Model ObservableRangeCollection<&
ListView ItemSource ObservableRangeCollection<> accessing Model ObservableRangeCollection<&

Time:03-14

I'm developing an .NET Xamarin App. I want to list all Products as ItemTemplate in the Grouped-ListView and Invoice.Name as Header. Currently I only get the GroupHeaderTemplate shown in my Grouped-ListView.

Model: Invoice.cs

public class Invoice : ObservableRangeCollection<Invoice>
{
    public string Name { get; set; }
    public Company Company { get; set; }
    public ObservableRangeCollection<Product> Products { get; set; }
}

Model: Products.cs

public class Product : ObservableRangeCollection<Product>
{
    public string Name { get; set; }
    public DateTime ExpireDate { get; set; }
}

ViewModel: MainViewVM (creating fake data)

public ObservableRangeCollection<Invoice> Invoices { get; set; }
public MainViewVM()
{
    Invoices.Add(new Invoice { Name = "Test1", Company = new Company { Image = image }, Products = new ObservableRangeCollection<Product>() { new Product { Name = "ProductTest1", CreatedDate = DateTime.Now }, new Product { Name = "ProductTest2", CreatedDate = DateTime.Now } } });
    Invoices.Add(new Invoice { Name = "Test2", Company = new Company { Image = image }, Products = new ObservableRangeCollection<Product>() { new Product { Name = "ProductTest3", CreatedDate = DateTime.Now }, new Product { Name = "ProductTest4", CreatedDate = DateTime.Now } } });
}

View: MainViewVM (ListView)

<ListView
IsGroupingEnabled="True"
ItemsSource="{Binding Invoices}">
<ListView.GroupHeaderTemplate>
    <DataTemplate x:DataType="models:Invoice">
        <ViewCell>
            <StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
                <Image Source="{Binding Company.Image}" WidthRequest="66" VerticalOptions="Center"/>
                <Label Text="{Binding Name}" VerticalOptions="Center"/>
            </StackLayout>
        </ViewCell>
    </DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
    <DataTemplate x:DataType="models:Product">
        <ViewCell>
            <StackLayout VerticalOptions="Center">
                <Label Text="{Binding Name}" VerticalOptions="Center"/>
            </StackLayout>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

CodePudding user response:

I added a constructor with : base. That fixed it for me. https://docs.microsoft.com/de-de/xamarin/xamarin-forms/user-interface/collectionview/grouping

public Invoice(string name, Company company, ObservableRangeCollection<Product> products) : base(products)
        {
            Name = name;
            Company = company;
            Products = products;
        }
  • Related