【问题标题】:Xamarin Forms ListView not showing TextCellsXamarin Forms ListView 不显示 TextCells
【发布时间】:2016-11-07 08:34:36
【问题描述】:

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

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 填充了两个没有内容的空白视图。

我错过了一些财产吗?

【问题讨论】:

    标签: c# listview xamarin xamarin.forms


    【解决方案1】:

    对于 ListView,ItemsSource 是包含数据的对象的集合,但它们本身不是 Views/Cells/其他 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;
                           })
                        }
                    }
                }
            };
    

    有关 ItemsSource/ItemTemplate 的更详细示例,请参阅 ListView 文档:https://developer.xamarin.com/api/type/Xamarin.Forms.ListView/

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 2019-12-29
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多