Windows Phone 8.1 图像加载到 UI 上

本文关键字:UI 加载 图像 Phone Windows | 更新日期: 2023-09-27 18:35:22

我们正在开发一个应用程序,该应用程序必须在运行时附加图像并将其显示在UI中。我们正在为它使用以下一组代码文件:

private void Btn_Attach_File_Click(object sender, RoutedEventArgs e)
{
            FileOpenPicker fileOpenPicker = new FileOpenPicker();
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".jpeg");
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.ContinuationData["Operate"] = "OpenImage";
            fileOpenPicker.PickSingleFileAndContinue();
          }  

另外,要在从存储中选取文件后继续应用,以下是代码:

public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if ((args.Files != null && args.Files.Count > 0))
            {
                IReadOnlyList<StorageFile> files = args.Files;
                Image myImage = new Image();
                foreach (StorageFile file in files)
                {
                    if (args.ContinuationData["Operate"] as string == "OpenImage" && args.Files !=          null && args.Files.Count > 0)
                    {
                        IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                        System.Diagnostics.Debug.WriteLine(file.Name);
                        System.Diagnostics.Debug.WriteLine(file.Path);
                        using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 190)) //, ThumbnailOptions.UseCurrentScale);
                        {
                            if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
                            {
                                BitmapImage bitmapImage = new BitmapImage();
                                bitmapImage.SetSource(thumbnail);
                                myImage.Source = bitmapImage;
                            }
                        }
                    }
                }
            }
        }

上面的代码在 xaml.cs 文件中。但问题是,即使我正在加载文件,UI 上也没有附件。是否需要对相应的 xaml 文件进行任何更改?我们已经搜索了很多,但找不到任何解决方案。

提前感谢,

Windows Phone 8.1 图像加载到 UI 上

首先,在 xaml 中创建一个图像控件:

<Image Name="img"/>

在循环后的代码隐藏中:

this.img.Source = myImage.Source;
//For better perf according to the docs, specify this
//this.img.Source.DecodePixelWidth = 200

当然,可以创建绑定而不是使用 Name 属性,但这是最简单的方法。

阅读文档: MSDN

另一件事,如果你有一个文件,循环foreach (StorageFile file in files)就没有那么有用,如果你有多个文件,它将占用最后一个文件。

请随时询问更多信息!

祝您编码:)愉快!