#listview #xamarin #xamarin.forms #datatemplate
#listview #xamarin #xamarin.forms #datatemplate
Вопрос:
Я пытался заполнить шаблон данных внутри 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.
РЕДАКТИРОВАТЬ: Рабочий код
Комментарии:
1. Эй, это работает?
2. Я еще не пробовал. Появилось кое-что еще. Сообщу вам, как только закончу.
Ответ №1:
Причина:
Label.Текст представляет собой строку.Но в вашем классе 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;
}
Ответ №2:
вы пропустили ItemSource для привязки в ListView xaml. Добавьте эту строку вместо
<ListView x:Name="listView" Grid.ColumnSpan="2">
Для
<ListView x:Name="listView" ItemsSource="{Binding DataDisplay}" Grid.ColumnSpan="2">
Комментарии:
1. Привет @Prashanth, это есть в части cs.
2. но вам также необходимо выполнить инициализацию в Xaml. Это коллекция, которая привязывает свойство к значениям ключа. Попробуйте этот
3. Проверьте, имеет ли ваше имя и оценка значения или null в DataDisplay
4. Это работает, когда я инициализирую name и оцениваю через array. Изменение списка на массив, а затем новые данные { name= Name[0], score = Оценка [0]} но это не тот подход, которому я хочу следовать, поскольку список всегда будет меняться по количеству.
5. Откуда вы передаете данные в name. Вы создаете с помощью ObservableCollection<Данные> .
Ответ №3:
public partial class MainPage : ContentPage
{
List<ScoreModel> ScoreList = new List<ScoreModel>();
List<NameModel> NameList = new List<NameModel>();
public MainPage()
{
InitializeComponent();
NameList.Add(new NameModel { Name = "Name1", Id = 0 });
NameList.Add(new NameModel { Name = "Name2", Id = 1 });
ScoreList.Add(new ScoreModel { Id = 0, Score = 1 });
ScoreList.Add(new ScoreModel { Id = 1, Score = 2 });
var DataDisplay = new List<Data>();
foreach (var item in NameList)
{
foreach (var item1 in ScoreList)
{
if(item.Id==item1.Id)
{
DataDisplay.Add(new Data { name = item.Name, score = item1.Score });
}
}
}
listView.ItemsSource = DataDisplay;
}
}
public class Data
{
public string name { get; set; }
public int score { get; set; }
}
public class NameModel
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ScoreModel
{
public int Id { get; set; }
public int Score { get; set; }
}
Ваш xaml:
<StackLayout>
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding name}" Grid.Column="0"
FontAttributes="Bold" />
<Label Text="{Binding score}"
Grid.Column="1" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Надеюсь, это может решить вашу проблему.