I want to make some changes to all of the cells shown in the ListView. Therefore I want to get all cells or items. E.g.
this.listView.ItemSource.Items
Items in the above code doesn't exist. Furthermore I didn't found any options on ListView
or ItemSource
, which could do this. Is it possible to get all cells/items? If not what other options do I have to change the appearence of the cells after they were loaded? E.g. for changing text or layout.
I am probably late to the party, but here's another approach using System.Reflection. Anyways, I'd suggest using it only in cases where databinding isn't possible and as a last resort option.
For a given ListView
You can crawl through the ListView by grabbing the "TemplatedItems" property, casting it to
ITemplatedItemsList<Cell>
and iterating through your (View)cells.Update: Since it was asked, if (cell.BindingContext != null && cell.BindingContext is MyModelClass) is basically a safeguard to prevent access to non-existing views, for instance if the ListView hasn't been populated yet.
If a check for the BindingContext being a particular model class isn't necessary, it would be sufficient to reduce the line to
Normally, you don't touch your cells directly. Instead, you try to do everything via data binding if it is possible.
Let's use the following Page defined in XAML:
In your Page, you set your ViewModel as BindingContext.
And your ViewModel contains your Items
MyItems
in an ObservableCollection, which means that your view updates, if you add or remove Items. This property is bound as ItemsSource of you List (see XAML:ItemsSource="{Binding MyItems}"
).For each Item, you have an object that represents the data of one cell. The type of this item implements
INotifyPropertyChanged
. That means, that it notifies which property has been changed. The data binding mechanism registers to this event and will update the view, when it is raised.If you now change one of the items, e.g. by calling
ChangeItem()
. Then the Label of the second cell will update to"Hello World"
, because it is bound to Title (see XAMLText="{Binding Title}"
).The general idea behind all this is called MvvM pattern, where you want to separate your view from the view logic and the model (data/services, ...).