Suppose you have a collection of items and you want to display them in a ListView (Xamarin.Forms). The catch is that you want to change the display of each item depending on its state or some other code-based attributes.
At first glance this would seem very difficult, and you’d have to modify the instances in the collection to do so. This is where the DataTemplateSelector comes in.
In short, you create two or more data templates — one for each way you might want to display one of the items in your collection — and then you tell Xamarin.Forms, by way of the DataTemplateSelector, which data template to use.
Quite often we want to send an alert from the view model, but you can only do so from the view. We’ve tackled this problem in the past but we think there is room for a simplified and clear step by step explanation.
We needed to put a picker inside a list view in a Xamarin.Forms app, but we wanted to be notified when one of the pickers changed and be able to get the value from the picker (and know which one changed).
The complete source for this example is on GitHub.
My first impulse was to use EventToCommand, but that became a rabbit hole, and thanks to Lance and others on the Xamarin Community Forums, and email, I was redirected to a simpler approach that I will explain here.
We begin with a DataTemplate that we will use with our ListView.
This is a quick summary of how I open a dialog box from the view model. There are other ways to do this (as noted in previous postings), but this is easy, easy to maintain and puts most of the logic in the view model.