0

With the following code I try to fill a stackpanel with some image controls. The for loop`` iterates over all images, whose path is in List<String> files;. Then the function fillPreviewBottom is called and returns an Image. Later, the array PreviewImages is used to add all controls as children.

private async void btnOpenFilesClick(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < files.Count; i++)
    {
        PreviewImages[i] = await fillPreviewBottom(files[i]);
    }
}

private async Task<Image> fillPreviewBottom(string file)
{

    Image img = new();
    BitmapImage bmImg = new();

    bmImg.BeginInit();

    bmImg.CacheOption = BitmapCacheOption.OnDemand;
    bmImg.DecodePixelWidth = 200;

    bmImg.EndInit();

    bmImg.UriSource = new Uri(file);

    img.Source = bmImg;
    img.Margin = new Thickness(5);

    return img;
}

Running this code return the error "Property 'UriSource' or property 'StreamSource' must be set.". Now I tried running this code

for (int i = 0; i < files.Count; i++)
{
    var s = new BitmapImage();
    s.BeginInit();
    s.UriSource = new Uri("sample.jpg");
    s.DecodePixelHeight = 10;
    s.EndInit();
    var im = new Image();
    im.Source = s;
    PreviewImages[i] = im;
}

bevor the the for loop where I load the actual pictures to 'init' all image with some sample picture but that did not work.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Max
  • 103
  • 7
  • Besides that there is nothing asynchronous in your fillPreviewBottom method, the error message means that you have to set UriSource (or StreamSource) before calling EndInit. – Clemens Jul 31 '23 at 09:58
  • See [this answer](https://stackoverflow.com/a/46709476/1136211) for an example how to load BitmapSources asynchronously. Or [this answer](https://stackoverflow.com/a/16041810/1136211). – Clemens Jul 31 '23 at 10:00

0 Answers0