How to change dynamically your listview using templates

Basically all the apps use a Listview to show one or more list of items.Sometimes you want to change the appearance of your items according to some parameter (for example inside the same page, sometimes you want to show partial forms, other times completed forms and so on).Let’s see how easily you can achieve this in Xamarin.

UI

First of all, we need to add a listview in our page:

<ListView ItemTemplate = "{Binding MyTemplate}" ItemsSource="{Binding MySource}" HasUnevenRows="True" VerticalOptions="FillAndExpand"></ListView>

With these few lines of code we have added a ListView that will vertically fill our page. We have also specified the ItemSource (the items we want to add to our listview), the ItemTemplate (the template to specify the appearance of our items) and set HasUnevenRows (true if we have items with different height, false otherwise).The UI is really easy! Isn’t it? Now let’s see how to specify the template.

TEMPLATE

Inside the ViewModel connected to our page we need to load MySource and MyTemplate:

...
public DataTemplate MyTemplate { get; set; }
        public ObservableCollection<MyItems> MySource { get; set; }

        public ListOfMyItemsViewModel(ItemType itemType)
        {
            MyTemplate = GetTemplate(itemType);
            MySource = new ObservableCollection<MyItems>(LocalData.GetMyItems(itemType));
        }

        private DataTemplate GetTemplate(ItemType itemType)
        {
            switch (itemType)
            {
                case ItemType.ItemType1: return new DataTemplate(typeof(CellType1));
                case ItemType.ItemType2: return new DataTemplate(typeof(CellType2));
                case ItemType.ItemType3: return new DataTemplate(typeof(CellType3));
                case ItemType.ItemType4: return new DataTemplate(typeof(CellType4));
            }

            return null;
        }
...

Inside the constructor we have specified the Template  for our cells and then we have loaded the Items.In this specific case (GetTemplate) we can load 4 different types of cell but of course we can have as many templates as we want. CellType1, CellType2, CellType3 and CellType4 are of type:  ViewCell. It’s important to note that in this example we have set the template inside the constructor (so when the page is loaded) but we can set it whenever we want so that for example we can change the appearance of our cells pressing a button or maybe selecting a value from a picker.

RECAP

With this few lines of code we can dynamically set the cell appearance in our listview according to the type of cell we want to load (specified in our case by itemType). 

Questions? Leave a message or send me an e-mail and I’ll answer you.