How do you implement value conversion in bindings?
Short answer
Implement IValueConverter (Convert and ConvertBack) to transform a source value into a target-friendly value, e.g., bool to color or enum to text. Declare the converter as a resource and reference it via Converter= in the binding.
Advertisement
AModel answer
Implement IValueConverter (Convert and ConvertBack) to transform a source value into a target-friendly value, e.g., bool to color or enum to text. Declare the converter as a resource and reference it via Converter= in the binding. Use ConvertBack for two-way scenarios; return BindableProperty.UnsetValue to skip.
public class BoolToColorConverter : IValueConverter
{
public object Convert(object v, Type t, object p, CultureInfo c)
=> (bool)v ? Colors.Green : Colors.Red;
public object ConvertBack(object v, Type t, object p, CultureInfo c)
=> throw new NotSupportedException();
}Real-world example
A status dot turns green or red by binding IsOnline through a BoolToColorConverter, keeping the view model free of UI colors.
Likely follow-ups
- When do you need ConvertBack? | How do you pass a ConverterParameter?
Related topics