listview - 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)从其他页面获取值。我不确定如何将其中的每个值与列表视图的名称和分数绑定。 编辑:工作代码
解决方案
原因:
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;
}
推荐阅读
- docker - 容器化 API 套接字挂起
- sql - 雪花枢轴
- python - 空列表条件
- docker - RazorSQL 和 sqldevelopper 无法使用 docker 连接到 Mac 上的 oracle DB
- php - Laravel - 如何使用where子句获取另一个表中不存在的数据
- mongodb - 如何在 MongoDB 中使用连接查询检索元素?
- ruby-on-rails - Rails 将结果选择成一个普通的旧 ruby 对象
- python - ModuleNotFoundError:Anaconda 中没有名为“pandas._libs.tslibs.base”的模块
- css - 我的弹性项目不会采用宽度和高度属性并保持在一条线上
- python - 函数内的python locals()包括在函数外导入的类