The usual behavior of a ListView is to display items as a list in a single column. The ItemSource property of Listview accepts the list of data to be displayed and rendered on the screen.
The code for a simple list to display the Students of a class would be as in the following image.
Now let's customize this ListView in a way to display the Student Name along with the Class and School they belong to.
As in the image above, the data contains a single record. So to accommodate the data in a single record, let's create a Student model class.
- public class Student
- {
- public string StudentName { get; set; }
- public string Class { get; set; }
- public string School { get; set; }
- }
In order to customize the ListView display, we need to override the ViewCell class.
- public class StudentCell : ViewCell
- {
- public StudentCell()
- {
- Label nameCell = new Label
- {
- TextColor = Color.Blue,
- FontSize = 30
- };
- nameCell.SetBinding(Label.TextProperty, "StudentName");
- Label classCell = new Label
- {
- TextColor = Color.Gray,
- FontSize = 20
- };
- classCell.SetBinding(Label.TextProperty, "Class");
- Label schoolCell = new Label
- {
- TextColor = Color.Gray,
- FontSize = 20
- };
- schoolCell.SetBinding(Label.TextProperty, "School");
- View = new StackLayout()
- {
- Children = { nameCell, classCell, schoolCell}
- };
- }
- }
We are done with the Model and the inherited ViewCell class, StudentCell. We will use the ItemTemplate attribute of ListView to assign the StudentCell class.
- List<Student> students = new List<Student>();
- students.Add(new Student() { StudentName = "Nirmal Hota", Class = "10th", School = "Bhagabati High School" });
- students.Add(new Student() { StudentName = "Tadit Dash", Class = "6th", School = "Student High School" });
- students.Add(new Student() { StudentName = "Suraj Sahoo", Class = "5th", School = "Khannagar High School" });
- students.Add(new Student() { StudentName = "Suvendu Giri", Class = "9th", School = "Baleswar High School" });
- students.Add(new Student() { StudentName = "Subhasish Pattanaik", Class = "8th", School = "Rourkela High School" });
-
- MainPage = new ContentPage
- {
- Content = new StackLayout
- {
- VerticalOptions = LayoutOptions.Center,
- Children = {
- new ListView(){
- ItemsSource = students,
- ItemTemplate = new DataTemplate(typeof(StudentCell)),
- HorizontalOptions=LayoutOptions.FillAndExpand
- }
- }
- }
- };
Let's run the app to see the new ListView.
Happy coding.