Programmatically set the Source of an Image (XAML)

后端 未结 7 692
孤街浪徒
孤街浪徒 2020-12-09 02:15

I am working on a Windows 8 app. I need to know how to programmatically set the Source of an Image. I assumed that the Silverlight approach would work. However, it doesn\'t.

7条回答
  •  执念已碎
    2020-12-09 03:04

    This example uses a FileOpenPicker object to obtain the storage file. You can use whatever method you need to access your file as a StorageFile object.

    Logo is the name of the image control.

    Reference the following code:

        var fileOpenPicker = new FileOpenPicker();
        fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
        fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        fileOpenPicker.FileTypeFilter.Add(".png");
        fileOpenPicker.FileTypeFilter.Add(".jpg");
        fileOpenPicker.FileTypeFilter.Add(".jpeg");
        fileOpenPicker.FileTypeFilter.Add(".bmp");
    
        var storageFile = await fileOpenPicker.PickSingleFileAsync();
    
        if (storageFile != null)
        {
            // Ensure the stream is disposed once the image is loaded
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                // Set the image source to the selected bitmap
                BitmapImage bitmapImage = new BitmapImage();
    
                await bitmapImage.SetSourceAsync(fileStream);
                Logo.Source = bitmapImage;
            }
        }
    

提交回复
热议问题