Search code examples
xamlxamarinxamarin.formsimagesource

Xamarin display list of imagesources in XAML


Is it possible to display a list of ImageSources in XAML with Xamarin like you do with an List of Strings? In string you would do:

<ListView x:Name="newsList" ItemsSource="{Binding newsList}" ItemTapped="listView_ItemTapped" IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshNewsCommand}" IsRefreshing="{Binding IsCurrentlyRefreshing}" /> 

However if you do this with an list of ImageSources it will not work. Does anyone know an appropriate way to load this list of images into my few? Preferably so that i can load them next to the items of my NewsList?


Solution

  • Yes, you can define an "ItemTemplate" on the ListView (xaml / c#). There are 2 predefined ViewCells that you can assign to the ItemTemplate. One of them is "ImageCell". But ImageCell displays an Image + Text.

    Also you might be interested in this: https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/customizing-cell-appearance/

    You will have to create a custom ViewCell.

    Something like this (pseudo code):

    ViewCell:
    
    <ViewCell>
        <ViewCell.View>
            <Image Source="{Binding CoolImageSource}" />
        </ViewCell.View>
    </ViewCell>
    
    //Your ListView, bring the namespace in, to reference your viewcell
    //You can also define the item directly inside of the DataTemplate
    //But keep your code clean and hold the viewcells separately
    <ListView xmlns:vc=YourNameSpace.ViewCellsFolder>
        <ListView.ItemTemplate>
            <DataTemplate>
                <vc:MyCoolViewCell />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    
    //And finally assign a List of such model:
    public class ImageItem 
    {
        public ImageSource CoolImageSource { get; set; }
    }