Xamarin

Learning about Converters in Xamarin Forms

When we are developing an application it is normal that we need to transfer data of the same type, as we already know to do this, we use Data Bindings. Doing this is very easy, especially if we can do the conversion implicitly. But what happens when we want to pass data with different values? To do it we use Converters and in this article we will be learning about it!


Let’s start!

First, let’s start learning the structure required:

This image has an empty alt attribute; its file name is Screen-Shot-2020-06-04-at-7.18.49-PM-1024x474.png

So now, let’s clarify some things: By using the IValueConverter  interface we have to implement two methods:

? Convert:        Is the method that will convert that received for a wished.

?ConvertBack: This returns the final value, here we can return a different value from the one received.


Both method receives four values  ?

This image has an empty alt attribute; its file name is Screen-Shot-2020-06-04-at-7.37.06-PM-1024x210.png

?  Value:               Value that will be converted.

?  Type:                 It’s the element type that is expected to be converted.

?  Parameter:     It’s an additional parameter which you can also convert.

 ?  CultureInfo:  The information about your culture.

Code implementation:

⚠ Important: When you name your converters it’s a best practice to meet the following criteria:

➖ First be explicit in indicating what your converter does. (For example: If you want to use a converter to to determine if you are a minor or an adult, for this a good name would be AgeToStatus)

➖ Second: It’s a converter! ?‍♀ Therefore try to indicate it clearly in the name, in the example above it would be AgeToStatusConverter! It will make your code more readable and intuitive!


And now, let’s use it in the XAML!

Add a namespace to your XAML indicating where your project is contained. (If you add them all in a folder called converter you can have your code more centralized and organized)

I added my Converter to my page ( ⭐ Don’t forget add the x:Key)

Finally to use in a property, just call your converter Converter={StaticResource IntToBoolConverter}

Congratulations! Your converter is ready! ?

Spanish post: https://medium.com/@reyes.leomaris/aprendiendo-sobre-converters-en-xamarin-forms-a74a2e7dcf54

Thanks for reading!!! ??

Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *