2
votes

Here is the code I am working with right now...

items = new List<TextCell>();
        items.Add(new TextCell { Text = "Cake", TextColor = Color.Green, Detail = "12 hours left!", DetailColor = Color.Black});
        items.Add(new TextCell { Text = "Pie", TextColor = Color.Green, Detail = "14 hours left!", DetailColor = Color.Black });


        var buy = new ContentPage
        {
            Title = "Buy",
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                    new ListView
                    {
                       ItemsSource = items,
                       ItemTemplate = new DataTemplate(typeof(TextCell))
                    }
                }
            }
        };

The ListView is populated with two blank views with no content.

Am I missing some property?

1

1 Answers

1
votes

With ListView, the ItemsSource is a collection of objects that contain data, but are not themselves Views/Cells/other UI objects. They are your domain data.

ItemTemplate, on the other hand, needs to return a Cell that has the right bindings set up so when the ListView sets its BindingContext to an object from ItemsSource, the fields are all set.

For your case, it might look like:

public class ThingToBuy
{
    public string What { get; set; }
    public string HowLong { get; set; }
}

items = new List<ThingToBuy>();
items.Add(new ThingToBuy { What = "Cake", HowLong = "12 hours left!" });
items.Add(new ThingToBuy { What = "Pie", HowLong = "14 hours left!" });

        var buy = new ContentPage
        {
            Title = "Buy",
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                    new ListView
                    {
                       ItemsSource = items,
                       ItemTemplate = new DataTemplate(() => {
                           var cell = new TextCell();
                           cell.SetBinding(Label.TextProperty, "What");
                           cell.SetBinding(Label.DetailProperty, "HowLong");
                           return cell;
                       })
                    }
                }
            }
        };

See documentation for ListView for more detailed example of ItemsSource/ItemTemplate: https://developer.xamarin.com/api/type/Xamarin.Forms.ListView/