コード例 #1
0
    /// <summary>
    /// Asynchronously loads the image for this control.
    /// </summary>
    private async void OnPreviewImageLoaded(object sender, RoutedEventArgs e)
    {
        try
        {
            // Set our temporary placeholder first
            var image = (Image)sender;
            image.Source = Imaging.GetPlaceholderIcon();

            // Now download the new image async.
            var package = image.DataContext as IDownloadablePackage;
            if (package?.Images == null || package.Images.Length <= 0)
            {
                return;
            }

            // Calculate actual rendered size.
            var tokenSource = new CancellationTokenSource();
            image.Unloaded += (o, args) =>
            {
                image.Loaded -= OnPreviewImageLoaded;
                tokenSource.Cancel();
            };

            var dpiScale     = VisualTreeHelper.GetDpi(image);
            var desiredWidth = (int)(image.DesiredSize.Width * dpiScale.DpiScaleX);

            // Select and decode appropriate image.
            var         uri    = package.Images[0].SelectBasedOnWidth(desiredWidth);
            BitmapImage?result = await Task.Run(async() =>
            {
                await using var memoryStream = new MemoryStream(await _cacheService.GetOrDownloadFileFromUrl(uri, _cacheService.ModPreviewExpiration, false, tokenSource.Token));

                if (!tokenSource.IsCancellationRequested)
                {
                    return(Imaging.BitmapFromStream(memoryStream, desiredWidth));
                }

                return(null);
            }, tokenSource.Token);

            if (!tokenSource.IsCancellationRequested)
            {
                image.Source = result;
            }
        }
        catch (Exception)
        {
            // ignored
        }
    }