Forum Xamarin.Forms

How to bind an image to a ListView template?

Hello, I'm trying to load icons to the menu page and want to use a template which will be bound to a collection of View Models. I have the text part working, but for some reason the icon doesn't.
I'm very sorry if the post is too long, I just don't know how else to show you the problem. Thanks in advance!

XAML:

<StackLayout VerticalOptions="FillAndExpand">
        <ListView x:Name="ListViewMenu" HasUnevenRows="True" >                
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="25" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Image Source="{Binding Icon}" Aspect="AspectFit" />
                            <Label Text="{Binding Title}" FontSize="20" Grid.Column="1" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Code Behind:

public partial class MenuPage : ContentPage
{
    MainPage RootPage { get => Application.Current.MainPage as MainPage; }
    List<HomeMenuItem> menuItems;
    public MenuPage()
    {
        InitializeComponent();

            menuItems = new List<HomeMenuItem>
            {
                // This is where I dictate the images' sources
                new HomeMenuItem {Id = MenuItemType.Home, Title="Home", Icon = new Image { Source = "home_blk.png" } },
                new HomeMenuItem {Id = MenuItemType.Holdings, Title="Holdings", Icon = new Image(){ Source = "show_chart_blk.png" }},
                new HomeMenuItem {Id = MenuItemType.Gain, Title="Gain", Icon = new Image(){ Source = "home_blk.png" } }
            };

            // This is where I set the ListView's source
            ListViewMenu.ItemsSource = menuItems;

            ListViewMenu.SelectedItem = menuItems[0];
            ListViewMenu.ItemSelected += async (sender, e) =>
            {
                if (e.SelectedItem == null) return;

                var id = (int)((HomeMenuItem)e.SelectedItem).Id;
                await RootPage.NavigateFromMenu(id);
            };
    }
}
public enum MenuItemType
{
    Home, Holdings, Gain
}
public class HomeMenuItem
{
    public Image Icon { get; set; }
    public MenuItemType Id { get; set; }
    public string Title { get; set; }
}

Best Answer

Answers

  • EitanEEitanE Member

    @Adeel984! That was so simple... I feel stupid :# . Thanks a lot! :)

  • Adeel984Adeel984 Member ✭✭✭

    You're welcome bro :smile:

Sign In or Register to comment.