Online and Offline status | Avalonia UI & MVVM

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

1- ViewModel

public partial class MainWindowViewModel : ViewModelBase
{
    [ObservableProperty]
    private bool _isOnline;

    public string Status => IsOnline ? "Online" : "Offline";

    public MainWindowViewModel()
    {
        IsOnline = true;
    }
}

2- BoolToColorConverter

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();
    }
}

3- Register Converter in App.axaml

<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>

4- View (MainWindow.axaml)

<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>

5- Add a Command to Toggle Status

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.
  • When IsOnline changes, the text changes to "Online" (green) or "Offline" (red).

Mohammed Chami
Mohammed Chami
Articles: 45

Leave a Reply

Your email address will not be published. Required fields are marked *