public async Task Initialize() { switch (CurrentType) { case BackgroundBrushType.Picture: { string UriString = Convert.ToString(ApplicationData.Current.LocalSettings.Values["PictureBackgroundUri"]); if (!string.IsNullOrEmpty(UriString)) { BitmapImage Bitmap = new BitmapImage(); StorageFile ImageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(UriString)); using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } PictureBackgroundBrush.ImageSource = Bitmap; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } else { Debug.WriteLine("UriString is empty, BackgroundController.Initialize is not finished"); } break; } case BackgroundBrushType.BingPicture: { BitmapImage Bitmap = new BitmapImage(); if (await BingPictureDownloader.DownloadDailyPicture().ConfigureAwait(true) is StorageFile ImageFile) { using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } BingPictureBursh.ImageSource = Bitmap; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } else { Debug.WriteLine("Download Bing picture failed, BackgroundController.Initialize is not finished"); } break; } } }
public async Task InitializeAsync() { if (!IsInitialized) { try { switch (CurrentType) { case BackgroundBrushType.Picture: { string UriString = Convert.ToString(ApplicationData.Current.LocalSettings.Values["PictureBackgroundUri"]); if (!string.IsNullOrEmpty(UriString)) { BitmapImage Bitmap = new BitmapImage(); PictureBackgroundBrush.ImageSource = Bitmap; try { StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri(UriString)); using (IRandomAccessStream Stream = await File.OpenReadAsync()) { await Bitmap.SetSourceAsync(Stream); } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } catch (Exception ex) { LogTracer.Log(ex, $"PicturePath is \"{UriString}\" but could not found, {nameof(BackgroundController.InitializeAsync)} is not finished"); } } else { LogTracer.Log($"PicturePath is empty, {nameof(BackgroundController.InitializeAsync)} is not finished"); } break; } case BackgroundBrushType.BingPicture: { if (await BingPictureDownloader.GetBingPictureAsync() is FileSystemStorageFile ImageFile) { BitmapImage Bitmap = new BitmapImage(); BingPictureBursh.ImageSource = Bitmap; using (IRandomAccessStream Stream = await ImageFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } else { LogTracer.Log("Download Bing picture failed, BackgroundController.Initialize is not finished"); } break; } } } catch (Exception ex) { LogTracer.Log(ex, "Exception happend when loading image for background"); } finally { IsInitialized = true; } } }