2016-11-06 60 views
2

這裏是我與現在使用的代碼...Xamarin窗體ListView不顯示TextCells

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控件填充了沒有內容兩個空的觀點。

我是否缺少一些房產?

回答

1

使用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/