Previous MAUI-Databinding MAUI-Pages Next

Value Converters in .NET MAUI

🔄 What Are Converters?

A Value Converter in MAUI is a class that implements IValueConverter. It lets you transform data during binding — for example, converting a bool into a Color, or a DateTime into a formatted string.

🎯 Why Do We Need Converters?

  • UI-friendly transformations: Data in your ViewModel may not be in the format the UI expects.
  • Avoid cluttering ViewModels: Keeps ViewModels clean by separating formatting logic.
  • Reusability: A converter can be reused across multiple bindings.

✅ When to Use Converters

  • When the source type ≠ target type (e.g., bool → Visibility).
  • When you need custom formatting (e.g., DateTime → "Jan 26, 2026").
  • When you want conditional UI changes (e.g., int → color based on threshold).
  • Type Mismatch: Converting raw data (like a numeric status code) into UI-friendly types (like a Color or ImageSource).
  • Logic Isolation: Keeping presentation logic out of your ViewModel. ViewModels should provide raw data; converters handle how that data is reshaped for the view.
  • Localization: Translating enums or codes into localized strings for different cultures.
  • Standard Toolkit Tasks: Using pre-built tools like the .NET MAUI Community Toolkit for common tasks like inverting booleans or checking for null.

🚫 When Not to Use Converters

  • If simple string formatting (StringFormat) or DataTemplateSelector can handle it.
  • When logic is business-related (keep that in ViewModel, not in converters).
  • For complex transformations — better handled in ViewModel properties.
  • Complex Business Logic: Converters should be simple and stateless. If the logic requires complex database calls or services, perform that in the ViewModel instead.
  • Simple String Formatting: Use the StringFormat property of a binding for basic text formatting instead of a custom converter.
  • Performance-Critical Loops: While the impact is often negligible, overusing heavy converters in large lists can affect scrolling performance.

⚡ Best Practices

  • Keep converters simple: One clear responsibility.
  • Make them reusable: Avoid hardcoding values.
  • Use MarkupExtension for inline converters if needed.
  • Test thoroughly: Ensure both Convert and ConvertBack work correctly in two-way bindings.
  • Prefer ViewModel logic for business rules: Converters are for presentation only.

⚠️ Pitfalls

  • Overusing converters: Leads to spaghetti bindings.
  • Complex logic inside converters: Hard to maintain/debug.
  • Forgetting ConvertBack: Breaks two-way binding if not implemented.
  • Performance issues: Too many converters can slow down rendering.

🧩 Example: Boolean to Color Converter

Converter Class

csharp
public class BoolToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool isActive = (bool)value;
        return isActive ? Colors.Green : Colors.Red;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Optional: only needed for TwoWay binding
        return (Color)value == Colors.Green;
    }
}
    

Usage in XAML

xml
<ContentPage.Resources>
    <ResourceDictionary>
        <local:BoolToColorConverter x:Key="BoolToColorConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

<Label Text="Status"
       TextColor="{Binding IsActive, Converter={StaticResource BoolToColorConverter}}" />
    

If IsActive = true → Label text is green.

If IsActive = false → Label text is red.


Example: Status to Color Converter

This converter changes a numeric status code from the ViewModel into a specific color for the UI.

1. The C# Converter Class

csharp
public class StatusToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int status)
        {
            return status switch
            {
                1 => Colors.Green, // Success
                0 => Colors.Red,   // Error
                _ => Colors.Gray   // Pending
            };
        }
        return Colors.Transparent;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
Use code with caution.
    

2. The XAML Usage

xml
<ContentPage.Resources>
    <local:StatusToColorConverter x:Key="StatusConverter" />
</ContentPage.Resources>

<Label Text="System Status" 
       TextColor="{Binding StatusCode, Converter={StaticResource StatusConverter
    

🏆 Summary

  • Converters = presentation logic helpers.
  • Use them for type mismatches or formatting.
  • Avoid them for business rules.
  • Keep them simple, reusable, and testable.
Back to Index
Previous MAUI-Databinding MAUI-Pages Next
*