Customizing Listview display in Xamarin
As the usual behavior of ListView to display the items in a list and it contains a single column. The ItemSource property of Listview accepts the list of data to be displayed and render the same on screen.
The code for a simple list to display the Students of a class would like as in the following pic.
Now let’s customize this ListView in a way to display the Student Name along with the Class and School they belongs 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.
1 2 3 4 5 6 7 8 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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 i.e. StudentCell. We will use the ItemTemplate attribute of ListView to assign the StudentCell class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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" }); // The root page of your application 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 🙂
Categories: Android, Cross Platform Mobile App, iOS, Visual Studio, Windows Phone, Xamarin