How to bind StaticResource to ImageSource in Xamarin.Forms AvatarView
In Xamarin.Forms SfAvatarView, you can set the key for ImageSource by using ResourceDictionary and bind image from ViewModel to ImageSource.
An ImageSource instance, can be either File, Uri or Resource, which sets the image to display.
ImageSource instances can be obtained by using any static methods for each type:
- FromFile - Requires a filename or file path that can be resolved on each platform.
- FromUri - Requires a Uri object, e.g. new Uri ("https://help.syncfusion.com/xamarin/avatar-view/images/avatarcharacter10.jpg ").
- FromResource - Requires a resource identifier to an image file embedded in the application or .NET Standard library project, with a Build Action:EmbeddedResource.
- FromStream - Requires a stream that supplies image data.
Local images
Image files can be added to each application project and referenced from Xamarin.Forms shared code.
- iOS - Images were typically placed in the Resources folder with Build Action: BundleResource.
- Android - Place images in the Resources/drawable directory with Build Action: AndroidResource. High- and low-DPI versions of an image can also be supplied (in appropriately named Resources sub-directories such as drawable-ldpi, drawable-hdpi, and drawable-xhdpi).
- Universal Windows Platform (UWP) - By default, images should be placed in the application's root directory with Build Action: Content.
Following steps describes how to use an image in Xamarin.Forms SfAvatarView
Step 1: Initialize the Xamarin.Forms SfAvatarView in XAML or code behind with the properties required.
Step 2: Add ViewModel class to show the images in Xamarin.Form.SfAvatarView.
Binding image from Static resource
XAML
<ContentPage.Resources> <ResourceDictionary> <x:String x:Key="avatarImage">Avatar.png</x:String> </ResourceDictionary> </ContentPage.Resources> <Grid> <avatarView:SfAvatarView ContentType="Custom" ImageSource="{StaticResource avatarImage}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="50" CornerRadius="25" WidthRequest="50" /> </Grid>
Binding image from ViewModel
ViewModel
public class AvatarViewModel : INotifyPropertyChanged { private ImageSource avatarImage = "Avatar.png"; public ImageSource AvatarImage { get { return avatarImage; } set { avatarImage = value; } } }
XAML
<ContentPage.BindingContext> <local:AvatarViewModel/> </ContentPage.BindingContext> <Grid> <avatarView:SfAvatarView ContentType="Custom" ImageSource="{Binding AvatarImage}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="50" CornerRadius="25" WidthRequest="50" /> </Grid>