I am very new to Xamarin Forms and I am trying to bind my Observable collection "DisplayItems" to my listview, but I cannot figure out how to do that and be able to display the name to the item. I can get the make listview.ItemsSource = DisplayItems
, but when I do I don't know how to make the label in the listview display to get the name of the Item. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ShoppingList
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public ObservableCollection<Item> DisplayItems;
public Page1()
{
InitializeComponent();
DisplayItems = new ObservableCollection<Item>();
DisplayItems.Add(new Item("potato", 3.40, 3, false));
DisplayItems.Add(new Item("juice", 4.70, 5, true));
BindingContext = this;
}
}
}
XAML:
<?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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="ShoppingList.Page1"
Title ="ViewPage">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="listview" ItemsSource="{Binding DisplayItems}" HasUnevenRows="True" HorizontalOptions="Fill" VerticalOptions="Fill" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="viewcell">
<StackLayout>
<Label x:Name="ListCell" Text="{Binding name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Having a look at this document about set model data for ListView. Data Binding in ListView .
You should define Item class as follow:
public class Item
{
public string name {get; set;}
}
Then in ContentPage add some data DisplayItems :
namespace ShoppingList
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public ObservableCollection<Item> DisplayItems;
public Page1()
{
InitializeComponent();
DisplayItems = new ObservableCollection<Item>();
DisplayItems .Add(new Item{ name="Rob Finnerty"});
DisplayItems .Add(new Item{ name="Bill Wrestler"});
BindingContext = this;
}
}
}
Last in Xaml this can work:
<ListView x:Name="listview" ItemsSource="{Binding DisplayItems}" HasUnevenRows="True" HorizontalOptions="Fill" VerticalOptions="Fill" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="viewcell">
<StackLayout>
<Label x:Name="ListCell" Text="{Binding name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.