Mohammed Chami
.NET Developer | Content Creator
Mohammed Chami
.NET Developer | Content Creator

This is a full working Avalonia UI + CommunityToolkit.MVVM example showing "Online" in green and "Offline" in red based on a bool IsOnline.


public partial class MainWindowViewModel : ViewModelBase
{
[ObservableProperty]
private bool _isOnline;
public string Status => IsOnline ? "Online" : "Offline";
public MainWindowViewModel()
{
IsOnline = true;
}
}
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool b)
{
return b ? Brushes.Green : Brushes.Red;
}
return Brushes.Gray;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="using:StatusBarExample.Converters"
x:Class="StatusBarExample.App">
<Application.Resources>
<conv:BoolToColorConverter x:Key="BoolToColorConverter" />
</Application.Resources>
</Application>
<StackPanel Margin="10" Spacing="8">
<TextBlock Text="{Binding Status}"
Foreground="{Binding IsOnline, Converter={StaticResource BoolToColorConverter}}"
FontSize="20"
FontWeight="Bold"/>
<Button Content="Toggle Status" Command="{Binding ToggleStatusCommand}" />
</StackPanel>
Update the ViewModel:
public partial class MainWindowViewModel : ObservableObject
{
[ObservableProperty]
private bool _isOnline;
public string Status => IsOnline ? "Online" : "Offline";
public MainWindowViewModel()
{
IsOnline = true;
}
[RelayCommand]
private void ToggleStatus()
{
IsOnline = !IsOnline;
OnPropertyChanged(nameof(Status)); // Update the text
}
}
How it works:
IsOnline is bound to the Foreground via BoolToColorConverter.Status is bound to the Text.IsOnline changes, the text changes to "Online" (green) or "Offline" (red).