WinRT、8.1、C#:动态地将图像设置为由 FileOpenPicker 选取的背景

本文关键字:设置 FileOpenPicker 选取 背景 图像 动态 WinRT | 更新日期: 2023-09-27 18:34:58

如何将选取的图像动态设置为网格的背景,将其保存在应用程序本地存储中并在每次启动应用程序时检索它?

    BitmapImage BgBitmap = new BitmapImage();
    Image BgImg = new Image();
    private async void bgbtn_Click(object sender, RoutedEventArgs e)
    {
        var fop = new FileOpenPicker();
        fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        fop.FileTypeFilter.Add(".jpg");
        fop.FileTypeFilter.Add(".png");
        fop.CommitButtonText = "OK";
        fop.ViewMode = PickerViewMode.Thumbnail;
        StorageFile file = await fop.PickSingleFileAsync();
        IRandomAccessStream stream= await file.OpenAsync(FileAccessMode.ReadWrite);
        await file.CopyAsync(ApplicationData.Current.LocalFolder, "BackgroundImg", NameCollisionOption.ReplaceExisting);
        await BgBitmap.SetSourceAsync(stream);
        BgImg.Source = BgBitmap;
    }

现在,如何将此 BgImg 设置为"主网格"网格背景?如果我可以将选择的文件保存在应用程序存储中并将该文件设置为背景,那就太好了。

WinRT、8.1、C#:动态地将图像设置为由 FileOpenPicker 选取的背景

var imageBrush = new ImageBrush();
imageBrush.ImageSource = BgBitmap;
this.mainGrid.BackGround = imageBrush;

这应该适合您