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!
First, let’s start learning the structure required:
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 🤔
📔 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.
⚠ 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
Congratulations! Your converter is ready! 🎊
Thanks for reading!!!