Share via

Displaying images in gridview using incremental loading

Priscillia Agnes 21 Reputation points
2022-07-06T03:10:48.317+00:00

I have a gridview that displays 435 images on a local package. I tried using Incremental Loading.

XAML:

<GridView
x:Name="komikGridView"
Margin="0,5,0,0"
Padding="0,0,10,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
BorderThickness="0"
Loaded="komikGridView_Loaded" Background="#FFBC9B9B" >
<GridView.Resources>
<DataTemplate x:Key="DataTemplatekomikGridView">
<Grid
x:Name="komikGrid1"
Margin="5,5,0,0"
Width="160"
Height="280"
Background="White">
<Image
x:Name="cover"
Grid.Row="0"
Width="160"
Height="235"
VerticalAlignment="Top"
Source="{Binding Image}"
Stretch="Fill" />
</Grid>
</DataTemplate>
</GridView.Resources>
<GridView.ItemTemplate>
<StaticResource ResourceKey="DataTemplatekomikGridView"/>
</GridView.ItemTemplate>
</GridView>

    <ProgressRing  
        x:Name="loading"  
        x:FieldModifier="public"  
        Width="60"  
        Height="60"  
        HorizontalAlignment="Center"  
        VerticalAlignment="Center"  
        Foreground="#FF3C7CDD" />  

Code:
private void komikGridView_Loaded(object sender, RoutedEventArgs e)
{
loading.IsActive = true;
komikGridView.ItemsSource = new ItemsToShow();
}

ItemsToShow Class:

public class ItemsToShow : ObservableCollection<Book>, ISupportIncrementalLoading  
    {  
        public int lastItem = 1;  
        public bool HasMoreItems  
        {  
            get  
            {  
                if (lastItem == 1000)  
                {  
                    return false;  
                }  
                else  
                {  
                    return true;  
                }  
            }  
        }  
  
        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)  
        {  
            ProgressRing progressRing = ((Window.Current.Content as Frame).Content as MainPage).loading;  
            CoreDispatcher coreDispatcher = Window.Current.Dispatcher;  
            return Task.Run<LoadMoreItemsResult>(async () =>  
            {  
                await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
                    () =>  
                    {  
                        progressRing.IsActive = true;  
                        progressRing.Visibility = Visibility.Visible;  
                    });  
  
                //List<string> items = new List<string>();  
                List<Book> items = new List<Book>();  
                StorageFolder localfolder = ApplicationData.Current.LocalFolder;  
                StorageFolder _pdffolder = Windows.ApplicationModel.Package.Current.InstalledLocation;  
                _pdffolder = await _pdffolder.GetFolderAsync("files");  
                _pdffolder = await _pdffolder.GetFolderAsync("pdf");  
                _pdffolder = await _pdffolder.GetFolderAsync("komik");  
                IReadOnlyList<StorageFile> _pdffiles = await _pdffolder.GetFilesAsync(); //which returns List<StorageFile>  
                                                                                       //Debug.WriteLine("pdf: " + _pdffolder.Path)  
                StorageFolder library = await localfolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);  
                StorageFolder komik = await library.CreateFolderAsync("komik", CreationCollisionOption.OpenIfExists);  
                IReadOnlyList<StorageFile> files = await komik.GetFilesAsync();  
  
                if (files.Count == 0)  
                {  
                    foreach (var item in _pdffiles)  
                    {  
                        await item.CopyAsync(komik, item.Name);  
                    }  
                }  
  
                IEnumerable<Temp> sortingFiles = files.Select(x => new Temp { File = x }).ToList();  
                foreach (var item in sortingFiles)  
                {  
                    //item.LastModified = (await item.File.GetBasicPropertiesAsync()).DateModified.DateTime;  
                    item.Name = item.File.Name;  
                }  
                IEnumerable<StorageFile> sortedfiles = sortingFiles.OrderByDescending(x => x.LastModified).Select(x => x.File).ToList();  
                StorageFolder _thumbfolder = Windows.ApplicationModel.Package.Current.InstalledLocation;  
                _thumbfolder = await _thumbfolder.GetFolderAsync("files");  
                _thumbfolder = await _thumbfolder.GetFolderAsync("cover");  
                _thumbfolder = await _thumbfolder.GetFolderAsync("komik");  
  
                IReadOnlyList<StorageFile> _coverfiles = await _thumbfolder.GetFilesAsync(); //which returns List<StorageFile>  
  
                StorageFolder thumbfolder = await localfolder.CreateFolderAsync("thumb", CreationCollisionOption.OpenIfExists);  
                StorageFolder komikthumb = await thumbfolder.CreateFolderAsync("komik", CreationCollisionOption.OpenIfExists);  
                IReadOnlyList<StorageFile> thumbfiles = await komikthumb.GetFilesAsync();  
                if (thumbfiles.Count == 0)  
                {  
                    foreach (var item in _coverfiles)  
                    {  
                        await item.CopyAsync(komikthumb, item.Name);  
                    }  
                }  
                          
                string filePath = "";  
                foreach (StorageFile file in sortedfiles)  
                {  
                    Book book = new Book();  
                    //FileItem book = new FileItem();  
                    book.Name = file.DisplayName.ToString();  
                    StorageFile thumbFile = await komikthumb.GetFileAsync(file.Name.ToString() + ".png");  
                    string path = komikthumb.Path;  
                    filePath = Path.Combine(path, file.Name.ToString() + ".png");  
  
                  await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
                  async () =>  
                    {  
                        BitmapImage bi = new BitmapImage();  
                        bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));  
                        book.Image = bi;  
                        Add(book);  
                    });  
                }  
                    await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
                    () =>  
                    {  
                        progressRing.Visibility = Visibility.Collapsed;  
                        progressRing.IsActive = false;  
                    });  
                return new LoadMoreItemsResult() { Count = count };  
            }).AsAsyncOperation<LoadMoreItemsResult>();  
        }  
  
        public class Temp  
        {  
            public StorageFile File { get; set; }  
            public DateTime LastModified { get; set; }  
            public string Name { get; set; }  
        }  
    }  

But I'm having a problem, i.e. the image doesn't display successfully on the gridview and when I check the LocalState folder, the folder is empty (the files were not copied successfully). How to handle it? And how to display 16 images first and when scrolled will display the next 16 images and so on?

Developer technologies | Universal Windows Platform (UWP)

Answer accepted by question author

Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,871 Reputation points
2022-07-06T09:24:30.607+00:00

Hello,
Welcome to Microsoft Q&A!

Displaying images in gridview using incremental loading

Please try to call LoadMoreItemsAsync manually like the following. And it's better that copy file to local foder before GridView load, the following is complete code.

 public class ItemsToShow : ObservableCollection<Book>, ISupportIncrementalLoading  
{  
    public int lastItem = 1;  
  
    public bool HasMoreItems  
    {  
        get  
        {  
            if (lastItem == 1000)  
            {  
                return false;  
            }  
            else  
            {  
                return true;  
            }  
        }  
    }  
  
    IReadOnlyList<StorageFile> files;  
    IReadOnlyList<StorageFile> thumbfiles;  
    StorageFolder komikthumb;  
    StorageFolder komik;  
    public async Task CopyResource()  
    {  
        await Task.Run(async () =>  
        {  
            StorageFolder localfolder = ApplicationData.Current.LocalFolder;  
            StorageFolder _pdffolder = Windows.ApplicationModel.Package.Current.InstalledLocation;  
            _pdffolder = await _pdffolder.GetFolderAsync("files");  
            _pdffolder = await _pdffolder.GetFolderAsync("pdf");  
            _pdffolder = await _pdffolder.GetFolderAsync("komik");  
            IReadOnlyList<StorageFile> _pdffiles = await _pdffolder.GetFilesAsync();   
            StorageFolder library = await localfolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);  
            komik = await library.CreateFolderAsync("komik", CreationCollisionOption.OpenIfExists);  
            files = await komik.GetFilesAsync();  
  
            if (files.Count == 0)  
            {  
                foreach (var item in _pdffiles)  
                {  
                    await item.CopyAsync(komik, item.Name, NameCollisionOption.ReplaceExisting);  
                }  
  
            }  
  
            StorageFolder _thumbfolder = Windows.ApplicationModel.Package.Current.InstalledLocation;  
            _thumbfolder = await _thumbfolder.GetFolderAsync("files");  
            _thumbfolder = await _thumbfolder.GetFolderAsync("cover");  
            _thumbfolder = await _thumbfolder.GetFolderAsync("komik");  
  
            IReadOnlyList<StorageFile> _coverfiles = await _thumbfolder.GetFilesAsync(); //which returns List<StorageFile>  
  
            StorageFolder thumbfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("thumb", CreationCollisionOption.OpenIfExists);  
            komikthumb = await thumbfolder.CreateFolderAsync("komik", CreationCollisionOption.OpenIfExists);  
            thumbfiles = await komikthumb.GetFilesAsync();  
            if (thumbfiles.Count == 0)  
            {  
                foreach (var item in _coverfiles)  
                {  
                    await item.CopyAsync(komikthumb, item.Name, NameCollisionOption.ReplaceExisting);  
                }                   
            }  
  
        });  
  
    }  
    public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)  
    {  
        ProgressRing progressRing = ((Window.Current.Content as Frame).Content as MainPage).loading;  
        CoreDispatcher coreDispatcher = Window.Current.Dispatcher;  
  
  
        return Task.Run<LoadMoreItemsResult>(async () =>  
        {  
            await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
           () =>  
           {  
               progressRing.Visibility = Visibility.Visible;  
               progressRing.IsActive = true;  
  
           });  
  
            files = await komik.GetFilesAsync();  
            IEnumerable<Temp> sortingFiles = files.Select(x => new Temp { File = x }).ToList();  
            IEnumerable<StorageFile> sortedfiles = sortingFiles.OrderByDescending(x => x.LastModified).Select(x => x.File).ToList();  
  
            
            string filePath = "";  
            foreach (StorageFile file in sortedfiles)  
            {  
                Book book = new Book();  
                book.Name = file.DisplayName.ToString();  
  
                StorageFile thumbFile = await komikthumb.GetFileAsync(file.Name.ToString() + ".png");  
                string path = komikthumb.Path;  
                filePath = Path.Combine(path, file.Name.ToString() + ".png");  
  
                await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
                async () =>  
                  {  
                      BitmapImage bi = new BitmapImage();  
                      bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));  
                      book.Image = bi;  
                      Add(book);  
                  });  
            }  
  
            await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,  
            () =>  
            {  
                progressRing.Visibility = Visibility.Collapsed;  
                progressRing.IsActive = false;  
            });  
  
            return new LoadMoreItemsResult() { Count = count };  
  
  
        }).AsAsyncOperation<LoadMoreItemsResult>();  
    }  
  
    public class Temp  
    {  
        public StorageFile File { get; set; }  
        public DateTime LastModified { get; set; }  
        public string Name { get; set; }  
    }  
}  

Usage

private async void KomikContent()  
{  
    var items = new ItemsToShow();  
    await items.CopyResource();  
    komikGridView.ItemsSource = items;  
    await items.LoadMoreItemsAsync(0);  
}  

Thank you.


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.