首页 > 解决方案 > Xamarin 表单列表视图“null”

问题描述

我需要用数据填充简单的 ListView,但 listView 仍然为空,我不知道为什么。代码(xaml):

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:SecuKey"
         x:Class="SecuKey.TransactionViewController">
<ListView x:Name="MainListView"  
         HasUnevenRows="True"  >  
   <ListView.ItemTemplate>  
       <DataTemplate>  
           <ViewCell>  
               <StackLayout Orientation="Vertical">  
                   <Label Text="{Binding Name}" />  
               </StackLayout>  
           </ViewCell>  
       </DataTemplate>  
   </ListView.ItemTemplate>  
 </ListView>  
</ContentPage>

和 c#:

using System;
using System.Collections.Generic;
using SecuKey.Controllers.ViewControllers;
using Newtonsoft.Json;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace SecuKey
{

public class ListViewTemplate
{
    public string Name { get; set; }

}
   
public partial class TransactionViewController : ContentPage
{
    public TransactionViewController()
    {
        // Just for test
        MainListView.ItemsSource = new List<ListViewTemplate> {
        new ListViewTemplate
            {
            Name = "Xamarin.Forms",
           },
           new ListViewTemplate
           {
               Name = "Android",
            },
            new ListViewTemplate
            {
                Name = "IOS",
           },
           new ListViewTemplate
           {
               Name = "Windows",
           }
       };
    }
 }

问题在这里: MainListView.ItemsSource = new List {} 因为 MainListView 为空...请提供任何建议?我跟着一个教程,没有更多的东西了..

谢谢

标签: xamarinxamarin.forms

解决方案


public MainPage()
    {
        InitializeComponent();
        List<ListViewTemplate> lists = new List<ListViewTemplate>();
        string[] N1 = { "Android", "Ios", "Windows" };
        for(int j=0;j< N1.Length; j++)
        {
            ListViewTemplate listView = new ListViewTemplate();
            listView.Name = N1[j];
            lists.Add(listView);
        }
        MainListView.ItemsSource = lists;
    }

推荐阅读