Borbin the 🐱

Xamarin - change image for ImageButton

21 April, 2020


For my project I'm working on I needed a button with an image that needs to be changed according to a state variable using XAML and MVVM. In this case, the changing image for a start / stop button:

Add the ImageButton to the MainPage.xaml:

<ContentPage.BindingContext>
    <local:MainPageViewModel />
</ContentPage.BindingContext>

<StackLayout>
    <ImageButton Source="{Binding StartStopImage}"
                 Command="{Binding StartStopCommand}"
                 WidthRequest="50"
                 HeightRequest="50"
                 HorizontalOptions="Center"
                 VerticalOptions="Center" >
    </ImageButton>

Add the implementation for MVVM:

    public MainPageViewModel()
    {
        StartStopCommand = new Command(async () => await StartStop());
    }


    public async Task StartStop()
    {
        recordEnabled = !recordEnabled;

        StartStopImage = recordEnabled ? "stop.png" : "start.png";
    }

    public Command StartStopCommand { get; }

    private string startStopImage = "stop.png";
    public string StartStopImage
    {
        get => startStopImage;
        set
        {
            startStopImage = value;
            OnPropertyChanged(nameof(StartStopImage));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }