using System.Linq; using System.Threading.Tasks; using CommunityToolkit.Diagnostics; using OwlCore.Extensions; using StrixMusic.Sdk.AppModels; using StrixMusic.Sdk.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Shapes; namespace StrixMusic.Sdk.WinUI.Controls { /// /// An control that displays an image, or a backup image if there is none. /// /// /// This control takes an and displays only the first, or none if none exist. /// [TemplatePart(Name = nameof(PART_ImageRectangle), Type = typeof(Rectangle))] public sealed partial class SafeImage : Control { /// /// Initializes a new instance of the class. /// public SafeImage() { DefaultStyleKey = typeof(SafeImage); } /// /// Dependency property for . /// public static readonly DependencyProperty ImageCollectionProperty = DependencyProperty.Register(nameof(ImageCollection), typeof(IImageCollectionViewModel), typeof(SafeImage), new PropertyMetadata(null, (inst, d) => inst.Cast().RequestImages().Forget())); /// /// The image collection to load and display. /// public IImageCollectionViewModel? ImageCollection { get { return (IImageCollectionViewModel?)GetValue(ImageCollectionProperty); } set { SetValue(ImageCollectionProperty, value); } } /// protected override void OnApplyTemplate() { // Find Parts PART_ImageRectangle = GetTemplateChild(nameof(PART_ImageRectangle)) as Rectangle; if (PART_ImageRectangle?.Fill is ImageBrush imgBrush) PART_ImageBrush = imgBrush; else ThrowHelper.ThrowInvalidDataException($"{nameof(PART_ImageRectangle)}'s fill must an ImageBrush."); _ = RequestImages(); base.OnApplyTemplate(); } private Rectangle? PART_ImageRectangle { get; set; } private ImageBrush? PART_ImageBrush { get; set; } private async Task RequestImages() { if (PART_ImageBrush is null) return; if (ImageCollection is null) { PART_ImageBrush.ImageSource = null; return; } var images = await ImageCollection.GetImagesAsync(1, 0).ToListAsync(); if (images.Count == 0) { PART_ImageBrush.ImageSource = null; return; } var image = images[0]; PART_ImageBrush.ImageSource = new BitmapImage(image.Uri) { DecodePixelHeight = (int)image.Height, DecodePixelWidth = (int)image.Width, }; } } }