dimanche 21 mars 2021

Xamarin forms : access controls inside a CarouselView

Hi everyone,

By working on one of my project, I had to implement the wonderful CarrouselView. Actually, I think this control was really well written because it takes into account MVVM in some important itemporperties and events (see mircosoft doc for more info)

But I spend some time on a problem: how can I access control inside this carrousel if I want to interact with one of the child control? This becomes a bit tricky.

As any dev, I start by google it,  and the anwser was blurry.

So I decided to do by my own:

Watchout: 

  • this solution described in this article is not the most elegant, but I will at the end give some tips in order to the clean the code 😃 
  • I volontary did not use MVVM due to the separtion of the UI and the "business". 


Here are the "data" sources  classes:


The xaml that manage the carousel. You can see that is composed with a boxview, a label and a button. No rocket science. This boxview displays a color, a label displays the name of the color, and the button wants to launch a message box (displayAlert) with a simple message

In the constructor, I bind my item source

Here comes then the problem, if we wants to find any control inside de carousel, there is no way to access it


So, instead of tying to access the value, we can by code retrieves the several childeren

Let's explain quickly how to find the conrols:

  1. Get the carrousel control via the command this.Content.FindByName<CarouselView>("MyCarrousel");
  2. Get all the control inside the carrousel control via the command: caroussel.VisibleViews;

By this, we have all the conrols inside the carousel. In my example, I have volontary added a Grid, once the grid accessed, I get the controls and now, I can work with them.

Clean code


It could have been over, but you and I knows that this code is not clean at all, and the main problem is if we change any position of a control, this code either use the wrong control or crash.

So instead of  using the index of the device, it's esier to loop (with a foreach loop) any childeren against the type of control used. (don't forget to cast when you find the device)
Once again, I intentionnaly don't show the full answer, just to let you exercice yoursel

have fun.