简体   繁体   中英

How do I display a list of images in uWP using MVVM

I would like to share how to display a list of images in UWP using MVVM.

In the Viewmodel you define the BitmapImages: (in this case 4 images called Tile0.jpg, Tile1.jpg, Tile2.jpg and Tile3.jpg located in the Assets folder in the project.

class ViewModel : INotifyPropertyChanged
{
    private readonly ObservableCollection<BitmapImage> m_tileBitmaps;
    public ObservableCollection<BitmapImage> TileBitmaps { get { return m_tileBitmaps; } }
    public ViewModel()
    {
        m_tileBitmaps = new ObservableCollection<BitmapImage>();

        for (int j = 0; j < 4; j++)
            {
                var bitmap =  new BitmapImage(new Uri(@"ms-appx:///Assets//Tile"+j.ToString() + ".jpg"));
                m_tileBitmaps.Add(bitmap);
            }
    }
}

In the view you can bind to the BitmapImages in this way:

            <ListView ItemsSource="{Binding TileBitmaps}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

It took me a while to figure that out. I hope it helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM