为什么添加数据模板会停止显示 itemssource?

Why does adding datatemplate stop the display of itemsource?

此代码会导致 table 中 230 条记录中的每条记录都显示相同行的 table 名称,但不包括以下字段:

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;

但是添加数据模板会导致空白屏幕

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;

首先,这在 XAML 中会更容易做到。但是如果你需要在代码中做到这一点

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;