繁体   English   中英

设置从ItemsSource到ListView DataTemplate中没有XAML的Label的绑定

[英]Set binding from ItemsSource to Label in ListView DataTemplate without XAML

我创建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 };
})

在添加到StackLayout之前初始化标签,例如bind其称为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 };
   })
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM