Reputation: 5594
i have a Xamarin ListView with images from internet. I would to show a default image (from embedded resource), and, when present, the image from an url.
I've tryied with this code but works only with UriImageSource, not for the embedded resource:
<ListView ItemsSource="{Binding Data}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Image>
<Image.Source>
<!-- does not works
<ImageSource>
{utils:ImageResource Namespace.Assets.img-placeholder.png}
</ImageSource>
-->
<UriImageSource Uri="{Binding ImageUri}"></UriImageSource>
</Image.Source>
</Image>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
if i use
<Image Source="{utils:ImageResource Namespace.Assets.img-placeholder.png}" />
this works showing the embedded resource default image
The model:
public Uri ImageUri => Image != null ?
new Uri($"http://www.example.com/{Image}")
: null;
Any help? Thanks
Upvotes: 0
Views: 1858
Reputation: 9703
You don't have to make it that complicated. From your viewmodel you simply provide a string ImageUri
and bind it to Image.Source
<Image Source="{Binding ImageUri}" />
this works for images from the web as well as resources, but they have to live in your platform projects. For Android you'll have to put them to Resources\drawable
(or the respective folders for other resolutions) and set the build action to AndroidResource, for iOS to Resources
(in different sizes with the @2x
, @3x
suffices, e.g. [email protected]
) and set the build action to bundle resource. You can now set the placeholder from your viewmodel:
if(!HasRemoteImage(response))
{
ImageUri = "img-placeholder.png";
}
Xamarin.Forms will create the ImageSource
automatically for you.
One main advantage over resources you load directly is, that you don't have to care which image is the right one for the current resolution. Xamarin/Xamarin.Forms does that automatically for you.
Upvotes: 1
Reputation: 2106
You can use FFImageLoading library.
According to its documentation:
LoadingPlaceholder
ImageSource property. If set, a loading placeholder is shown while loading. It supports UriImageSource, FileImageSource and StreamImageSource.
ErrorPlaceholder
ImageSource property. If set, if error occurs while loading image, an error placeholder is shown. It supports UriImageSource, FileImageSource and StreamImageSource.
Upvotes: 1