Search code examples
c#restxamarinmvvmservice

How to Show Image from Restful Service to Xamarin.Forms View with MVVM


I have a Restful Service which provides me Image as a stream. When I call that service into the browser to show image it works well there too. Now I am trying to show that image in the Xamarin View like this:

<ffimageloading:CachedImage Source="{Binding ImageSource}" Aspect="AspectFill" WidthRequest="75" HeightRequest="200"></ffimageloading:CachedImage>

ViewModel contains the following functionality:

private ImageSource _imageSource;
public ImageSource ImageSource
{
    get { return _imageSource; }
    set
    {
        _imageSource = value;
        SetProperty(ref _imageSource, value);
    }
}
private string itemId;
public string ItemId
{
    get
    {
        return itemId;
    }
    set
    {
        itemId = value;
        LoadItemId(value);
    }
}

public async void LoadItemId(string itemId)
{
    try
    {
        var item = await MockDataStore.GetItemAsync(itemId);
        Id = item.ID;
        Text = item.TITLE;
        Description = item.CONTENT;
        //ImageSource = "http://127.0.0.1:4321/Service.svc/GetImage/?uri=12";
        ImageSource = "https://www.shareicon.net/data/128x128/2016/05/02/758874_package_512x512.png";
    }
    catch (Exception)
    {
        Debug.WriteLine("Failed to Load Item");
    }
}

When I provide image link directly in the Source of the image in view it works perfectly.

<ffimageloading:CachedImage Source="https://www.shareicon.net/data/128x128/2016/05/02/758874_package_512x512.png" Aspect="AspectFill" WidthRequest="75" HeightRequest="200"></ffimageloading:CachedImage>

But when I try to get ImageSource from ViewModel, none is showing image on view neither the service call nor any image link. The strange thing which I have seen while debugging is that whenever I change anything in the view which activates the Hot Reload it suddenly shows the image from ViewModel in the emulator. I am new to Xamarin and don't know how to get it resolved.


Solution

  • Your VM doesn't implement INotifyPropertyChanged, put that in place and signal the change to ImageSource for the view/xaml.