I Would like to display something like nested listview in Xamarin forms.
I mean i would like to have list of Person with theirs orders (the list of order could be empty). The List would allow to add order to specific person, remove person (and all of his orders), and remove specific order.
I Considerd to create ListView of OrderModel where OrderModel would looks like:
public class OrderModel
{
public string PersonName {get;set;}
public Order Order {get; set;}
}
But I dont know if this is a good idea, and how to implement something like this.
I write a simple demo to achieve your requirement. I use the Grouped ListViews
:
OrderModel:
public class OrderModel
{
public string orderName { get; set; }
public OrderModel()
{
}
}
public class GroupedOrderModel : ObservableCollection<OrderModel>
{
public string personName { get; set; }
}
Set the dataSource:
public partial class GroupedListXaml : ContentPage
{
private ObservableCollection<GroupedOrderModel> grouped { get; set; }
public GroupedListXaml ()
{
InitializeComponent ();
grouped = new ObservableCollection<GroupedOrderModel> ();
var person1Group = new GroupedOrderModel() { personName = " john"};
var person2Group = new GroupedOrderModel() { personName = " alex"};
var person3Group = new GroupedOrderModel() { personName = " jack"};
person1Group.Add (new OrderModel () { orderName = " OrderOne"});
person1Group.Add (new OrderModel() { orderName = " OrderTwo" });
person1Group.Add (new OrderModel() { orderName = " OrderThree"});
person1Group.Add (new OrderModel() { orderName = " OrderFour"});
person2Group.Add (new OrderModel() { orderName = " OrderOne"});
person2Group.Add (new OrderModel() { orderName = " OrderTwo"});
person2Group.Add (new OrderModel() { orderName = " OrderThree"});
grouped.Add (person1Group);
grouped.Add (person2Group);
//Person3 without OrderModel
grouped.Add(person3Group);
lstView.ItemsSource = grouped;
}
}
In XAML, use ListView.GroupHeaderTemplate
to customize the group header:
<ContentPage.Content>
<ListView x:Name ="lstView" IsGroupingEnabled="true" Footer="">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding orderName}" VerticalOptions="Center" HorizontalOptions="StartAndExpand"/>
<Button Text="remove " HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding personName}" VerticalOptions="Center" HorizontalOptions="StartAndExpand"/>
<Button Text="remove all " TextColor="Red" HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
</ListView>
</ContentPage.Content>
Let's have a look at result:
how can I display person3 if his items list is empty?
Check the dataSource
code and Person3 has no orderModel
.