Can't iterate over ListView Items in Xamarin Forms

When I write this code:

ListView lv = new ListView();

foreach (ListViewDataItem item in lv.Items)
{

}

I get "the type or name ListViewDataItem could not be found"

Items is also not found under the lv object.

Basically I need to iterate through each row of the ListView and set a checkbox added using item template.

How can I accomplish that?

Upvotes: 3

Views: 6370

Answers (2)

Dr. Matthew Kwiecien
Dr. Matthew Kwiecien

Reputation: 11

I used a for loop to iterate over my listView ChildCount, assigned a var as the Tag of the GetChildAt as ImageAdapterViewHolder and then set my checkbox to false.

class ImageAdapterViewHolder : Java.Lang.Object
{
    public ImageView SavedImage { get; set; }
    public TextView Description { get; set; }
    public CheckBox SelectImage { get; set; }

}

for (int i = 0; i < listView.ChildCount; i++)
{
    var row = listView.GetChildAt(i).Tag as ImageAdapterViewHolder;
    row.SelectImage.Checked = false;
}

Upvotes: 0

Patrick
Patrick

Reputation: 1737

The correct way to loop through a listview is to access it's ItemsSource. Then you can cast the item into your view model and do stuff with it.

foreach (var item in lv.ItemsSource)
{
    // cast the item 
    var dataItem = (ListViewDataItem) item;

    // then do stuff with your casted item
    ...
}

Upvotes: 2

Related Questions