Customizing ListView Display in Xamarin
Join the DZone community and get the full member experience.
Join For Freeas 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.
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 i.e.
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" }); // 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
Published at DZone with permission of Nirmal Hota, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments