【问题标题】:Set binding from ItemsSource to Label in ListView DataTemplate without XAML在没有 XAML 的 ListView DataTemplate 中设置从 ItemsSource 到 Label 的绑定
【发布时间】:2017-02-20 07:06:36
【问题描述】:

我为我的ListView 创建了DataTemplate,但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 };
})

【问题讨论】:

    标签: c# xamarin binding


    【解决方案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 };
       })
    };
    

    【讨论】:

    • 但是如果我需要将我的 ItemSource 与字符串列表绑定,我必须使用什么第二个参数?
    • 更新了@InfernumDeus
    猜你喜欢
    • 2014-12-08
    • 2012-10-14
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2017-08-05
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多