我一直在尝试填充 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; }
}
我有两个列表(名称和分数),它们从其他页面获取值。我不知道如何将其中的每个值与 ListView 的名称和分数绑定(bind)。 编辑:工作代码
最佳答案
原因:
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;
}
关于Xamarin 表单中的 ListView 数据模板绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155422/