Hello! I have a question: I want to download, being on the start page of my program, pictures from the Internet and, through a certain function, assign their collections.

After that, I turn from the start page of the program to the page with pictures, but there is some hangup of the program interface, as can be seen from the Dispatcher code, but I don’t. and I don't know what to do.

A piece of WPF, this is a “Tile” ratio of 5 x 6 images:

<ItemsControl Grid.Row="0" ItemsSource="{Binding RecentMedias}" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="5" Rows="6" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Border Width="176" Height="247" Margin="20,20,0,0"> <Grid> <Image Source="{Binding Path=Images, IsAsync=True}"/> </Grid> </Border> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 

C # chunk:

 for (int i = 0; i < RecentMedias.Count(); i++) { int temp = i; Task.Factory.StartNew(() => { DownloadInst(RecentMedias[temp]); }); } public void DownloadInst(SelectedMedia m) { while (m.DownloadError) { try { System.Net.WebRequest request = System.Net.WebRequest.Create(m._Media.Images.LowResolution.Url); System.Net.WebResponse response = request.GetResponse(); var memoryStream = new MemoryStream(); using (System.IO.Stream responseStream = response.GetResponseStream()) { responseStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); } BitmapImage image = new BitmapImage(); image.BeginInit(); image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = memoryStream; image.EndInit(); image.Freeze(); m.Images = image; m.DownloadError = false; } catch { Thread.Sleep(1000); App.Log.Write("Не удалось скачать инстаграмм"); } } } 

    1 answer 1

    Look maybe you have, somewhere null. Look at the number of items in the collection. I use the code to upload pictures:

     public void AddImages(string[] images) { if (_images == null) ImagesScroll._images = new ObservableCollection<BitmapImage>(); foreach (var link in images) { try { var imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.UriSource = new Uri(link); imageSource.EndInit(); ImagesScroll._images.Add(imageSource); } catch (System.Net.WebException ex) { MessageBox.Show(ex.Message); } } } 
    • But I am downloading images in separate streams and are not loaded into the interface of the loaded page immediately. - A. Mikhail
    • But you checked under the debug collection of pictures is not equal to null and there are pictures in it. BitmapImage independently in a separate stream downloads the image and there is no need to get the image using WebRequest. - Alexsandr Ter