首页 文章

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

提问于
浏览
1

This is for my Windows 8 app:

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

public String ImagePath

在我的XAML中,我设置了一个带有以下绑定的Image标签:

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

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

但是,当我引用用户选择的图像时(使用FilePicker),我收到错误( and no image ) . 路径是: C:\Users\Jeff\Pictures\myImage.PNG

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

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

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

Update:

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

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

我尝试为我的模型创建一个BitmapImage属性,但现在我收到错误声明它无法序列化BitmapImage .

4 回答

  • 1

    你应该使用转换器

    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();
            }
        }
    
  • 1

    您不能使用指向app目录之外的文件路径 . 您将需要读入从文件选择器获取的StorageFile流并将该流分配给图像源 - 因此,除非您更改模型,否则绑定非常困难,而是拥有一个imagesource属性 .

  • 1

    如上所述,即使您通过文件选择器授予访问权限,也无法使用绑定直接访问文件系统 . 有关您可以使用的技术,请查看Dev Center处的XAML Images Sample .

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

  • 6

    我最近做了一些关于绑定到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 []中的图像 . 您可以将图像转换为byte [],也可以尝试使用FileStream(我没有使用FileStream进行测试,所以我不能说它是否可行) .

相关问题