| MAUI-Databinding | MAUI-Pages | |
Value Converters in .NET MAUI |
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.
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.
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.
xml
<ContentPage.Resources>
<local:StatusToColorConverter x:Key="StatusConverter" />
</ContentPage.Resources>
<Label Text="System Status"
TextColor="{Binding StatusCode, Converter={StaticResource StatusConverter
| MAUI-Databinding | MAUI-Pages | |