2

这适用于我的 Windows 8 应用程序:

在我的对象中,我有一个字符串属性,其中包含我要使用的图像的路径。

public String ImagePath

在我的 XAML 中,我设置了一个带有以下绑定的图像标记:

<Image Source="{Binding ImagePath}" Margin="50"/>

当我引用包含在我的项目中(在 Asset 文件夹中)的图像时,图像会正确显示。路径是:Assets/car2.png

但是,当我引用用户选择的图像(使用 FilePicker)时,我得到一个错误(并且没有图像)。路径是:C:\Users\Jeff\Pictures\myImage.PNG

转换器无法将“Windows.Foundation.String”类型的值转换为“ImageSource”类型

只是为了添加更多信息。当我使用文件选择器时,我将文件位置转换为 URI:

        Uri uriAddress =  new Uri(file.Path.ToString());
        _VM.vehicleSingle.ImagePath = uriAddress.LocalPath;

更新:

我还将此图像路径保存到独立存储中。我认为这就是问题所在。我能够保存所选文件的路径,但是当我在重新加载独立存储时尝试绑定它时,它不起作用。

因此,如果我不能在应用程序目录之外使用图像。有没有办法可以保存该图像并将其添加到目录中?

我尝试为我的模型创建一个 BitmapImage 属性,但现在我收到错误消息,指出它无法序列化 BitmapImage。

4

4 回答 4

7

你应该使用转换器

public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            MemoryStream memStream = new MemoryStream((byte[])value,false);
            BitmapImage empImage = new BitmapImage();
            empImage.SetSource(memStream);
            return empImage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
于 2013-02-04T05:45:32.160 回答
1

您不能使用指向应用程序目录之外的文件路径。您将需要读取从文件选择器获得的 StorageFile 流,并将该流分配给图像源 - 因此,除非您更改模型,否则绑定非常困难,改为具有 imagesource 属性。

于 2013-01-27T17:15:10.157 回答
1

我最近做了一些绑定到 ImageSource 的工作。

public System.Windows.Media.ImageSource PhotoImageSource
{
    get
    {
         if (Photo != null)
         {
              System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
              image.BeginInit();                    
              image.StreamSource = new MemoryStream(Photo);
              image.EndInit();

              return image as System.Windows.Media.ImageSource;
          }
          else
          {
               return null;
          }
     }
}

我的“照片”是存储在字节 [] 中的图像。您可以将图像转换为 byte[] 或者尝试使用 FileStream 代替(我没有使用 FileStream 进行测试,所以我不能说它是否会工作)。

于 2013-02-01T20:09:41.930 回答
1

如前所述,您不能使用绑定直接访问文件系统,即使您通过文件选择器授予访问权限。查看开发中心的XAML 图像示例,了解您可以使用的技术。

简而言之,您将使用SetSourceAsync将文件放入BitmapImage,然后您可以将其用作绑定源。

于 2013-01-27T18:33:30.053 回答