Search code examples
xamarindatatemplate

Why does adding datatemplate stop the display of itemsource?


This code results in a display of the same line of the table name for every one of the 230 records in the table but not the fields:

ListView lv = new ListView();
        lv.ItemsSource = await App.Database.GetItemsAsync();
        StackLayout sl = new StackLayout();
        
        Label ln = new Label();
        ln.SetBinding(Label.TextProperty, nameof(ContactsModel.LastName));
        Label fn = new Label();
        fn.SetBinding(Label.TextProperty, nameof(ContactsModel.FirstName));
       
        sl.Children.Add(ln);
        sl.Children.Add(fn);
        sl.Children.Add(lv);
        Content = sl;

But adding the datatemplate results in a blank screen

ListView lv = new ListView();
            lv.ItemsSource = await App.Database.GetItemsAsync();
            var template = new DataTemplate(typeof(ViewCell));
            lv.ItemTemplate = template;
            StackLayout sl = new StackLayout();
            
            Label ln = new Label();
            ln.SetBinding(Label.TextProperty, nameof(ContactsModel.LastName));
            Label fn = new Label();
            fn.SetBinding(Label.TextProperty, nameof(ContactsModel.FirstName));
           
            sl.Children.Add(ln);
            sl.Children.Add(fn);
            sl.Children.Add(lv);
            Content = sl;

Solution

  • first, this would be easier to do in XAML. But if you need to do it in code

    var template = new DataTemplate(() =>
    {
        Label ln = new Label();
        ln.SetBinding(Label.TextProperty, nameof(ContactsModel.LastName));
        Label fn = new Label();
        fn.SetBinding(Label.TextProperty, nameof(ContactsModel.FirstName));
            
        var stack = new StackLayout();
        stack.Children.Add(ln);
        stack.Children.Add(fn);
    
        return new ViewCell { View = stack };
    });
    
    lv.ItemTemplate = template;