在没有XAML的ListView DataTemplate中将ItemsSource中的绑定设置为Label

时间:2017-02-20 07:06:37

标签: c# xamarin binding

我为DataTemplate创建了ListView,但ListViewItems的文字未显示。如何绑定ItemsSource的文字?

List<string> stringList;

ListView myListView = new ListView 
{
    ItemsSource = stringList,
    ItemTemplate = new DataTemplate(() => 
    {
        StackLayout sl = new StackLayout 
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Orientation = StackOrientation.Horizontal,
        };
        sl.Children.Add(new Label 
        {
            FontSize = 14,   
        });

        return new ViewCell { View = sl };
})

1 个答案:

答案 0 :(得分:1)

在添加到StackLayout之前初始化您的标签,例如将其称为temp,将bind称为自定义对象:

temp.SetBinding (Label.TextProperty, "TemplatePropertyThatYouWish");

这是一个字符串列表:

temp.SetBinding(Label.TextProperty, ".");

然后将其添加到StackLayout。

代码:

List<string> stringList = new List<string> { "a", "b", "c" };

ListView myListView = new ListView
{
    ItemsSource = stringList,
    ItemTemplate = new DataTemplate(() =>
    {
        StackLayout sl = new StackLayout
        {
             VerticalOptions = LayoutOptions.FillAndExpand,
             Orientation = StackOrientation.Horizontal,
        };

        var temp = new Label
        {
            FontSize = 14,
        };

        temp.SetBinding(Label.TextProperty, ".");

        sl.Children.Add(temp);

        return new ViewCell { View = sl };
   })
};