Xamarin Forms列表视图不显示文本单元格

本文关键字:显示 文本 单元格 视图 Forms 列表 Xamarin | 更新日期: 2023-09-27 18:16:40

这是我现在正在使用的代码…

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))
                    }
                }
            }
        };

ListView用两个没有内容的空白视图填充。

我遗漏了一些属性吗?

Xamarin Forms列表视图不显示文本单元格

对于ListView, ItemsSource是包含数据的对象集合,但它们本身不是视图/单元格/其他UI对象。它们是您的域数据。

另一方面,

ItemTemplate需要返回一个设置了正确绑定的Cell,这样当ListView将它的BindingContext设置为来自ItemsSource的对象时,字段就都设置好了。

对于您的情况,它可能看起来像:

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;
                       })
                    }
                }
            }
        };

查看ListView文档获取ItemsSource/ItemTemplate的更详细示例:https://developer.xamarin.com/api/type/Xamarin.Forms.ListView/