How to show alternate text if image loading failed in .net maui?

Thombre, Ashish 130 Reputation points
2024-07-02T13:27:11.05+00:00

<Image x:Name="img" Source="{Binding Image}" Aspect="AspectFill" Margin="2" IsVisible="{Binding IsImage}">

</Image>

I am using above code to show image. Additionally, i want to show alternate text if image loading is failed.

Platform- Android

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,607 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,551 Reputation points Microsoft Vendor
    2024-07-03T06:15:39.1633333+00:00

    Hello,

    MAUI Image control does not have this function, please add a feature request in the MAUI GitHub repro.

    Here is a workaround, you can add Label and Image in the Grid like following layout. By default, the label's Text is null

    <Grid>
    <Label x:Name="loadFailedLabel"  HorizontalOptions="Center" VerticalOptions="Center"></Label>
      <Image
      Source="
    https://aka.ms/campus1.jpg"
       x:Name="img"
      Loaded="Image_Loaded"
      HeightRequest="185"
      Aspect="AspectFit"
    />
      
    </Grid>
    

    When load failed, you get the null value from img.Source.GetPlatformImageAsync(Handler.MauiContext);, then you can set the Text to this Label.

    private async void Image_Loaded(object sender, EventArgs e)
      {
          var res = await img.Source.GetPlatformImageAsync(Handler.MauiContext);
          if (res == null)
          {
              loadFailedLabel.Text="this is a Image but load Failed";
          }else{
              loadFailedLabel.Text="";
         }
      }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.