首页 > 解决方案 > Xamarin 表单中的 ListView 数据模板绑定

问题描述

我一直在尝试在列表视图中填充数据模板,但它没有显示任何内容。我的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
         x:Class="BlueDemo.ScoreDisplay">
<ContentPage.Content>                 
       <StackLayout> 
        <ListView x:Name="listView" Grid.ColumnSpan="2">
           <ListView.ItemTemplate>
           <DataTemplate>
              <ViewCell>
                <Grid>
                  <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="0.7*"/> 
                     <ColumnDefinition Width="0.3*"/> 
                  </Grid.ColumnDefinitions>     
                  <Label Text="{Binding name}" FontAttributes="Bold"/>
                  <Label Text="{Binding score}" Grid.Column ="1"/>                
                </Grid>
              </ViewCell>
          </DataTemplate>
          </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>    

public partial class ScoreDisplay : ContentPage
{
    public static List<int> Score = new List<int>();
    public static List<string> Name = new List<string>();
     public string[] nme = new string[10];

    public static int[] scr = new int[10];

    public ObservableCollection<Data> mySource{get;set;}
    public ScoreDisplay()
    {
        InitializeComponent();
        BindingContext = this;


        nme = Name.ToArray();
        scr=Score.ToArray();

        mySource = new ObservableCollection<Data>();
        for(int i=0;i<nScore.Count;i++)
        {
            mySource.Add(nnew Data {name = nme[i], score = 
            scr[i].ToString()});
        }
        listView.ItemsSource = mySource;
    }  
}

public class Data
{
   public string name { get; set; }
   public string score { get; set; } 
}

我有两个列表(Name 和 Score)从其他页面获取值。我不确定如何将其中的每个值与列表视图的名称和分数绑定。 编辑:工作代码

标签: listviewxamarinxamarin.formsdatatemplate

解决方案


原因:

Label.Text 是一个字符串。但是在你的类Data中,属性名称是一个List

解决方案:

请参考以下代码。

public class Data
{
    public string name { get; set; }
    public string score { get; set; }
}

public ObservableCollection<Data> mySource { get; set; }

List<int> ScoreList = new List<int>();
List<string> NameList = new List<string>();    

public ScoreDisplay ()
{
  InitializeComponent();

  BindingContext = this;

  NameList.Add("jack");
   // or you can set the list with  the other part of the app

  ScoreList.Add(60);
   //...

  mySource = new ObservableCollection<Data>();

  for (int i=0;i<ScoreList.Count;i++)
   {
      mySource.Add(new Data { name = NameList[i], score = ScoreList[i].ToString()});
   }


  listView.ItemsSource = mySource;
}

推荐阅读