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

标签 xaml windows-8

这是我的 Windows 8 应用程序:

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

public String ImagePath

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

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

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

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

Converter failed to convert value of type 'Windows.Foundation.String' to type 'ImageSource'

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

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

更新:

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

所以如果我不能在应用程序目录之外使用图像。有什么方法可以保存该图像并将其添加到目录中吗?

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

最佳答案

你应该使用转换器

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

关于xaml - 转换器无法将类型 'Windows.Foundation.String' 的值转换为类型 'ImageSource',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14546296/

相关文章:

c# - 如何在 Binding StringFormat 中使用变量文本?

c# - WPF 矩形边框与两条破折号的连接线的角

windows-8 - Windows 8 WinRT KeyboardCapabilities.KeyboardPresent 始终为真

c# - Metro 应用程序中的 FTP

windows-8 - Windows 8 中的动态磁贴隐藏小 Logo 图像

.net - 自定义 WPF DatePickerTextBox 模板

.net - 如何将程序集 BAML 转换为 XAML?

c# - Xamarin Forms 框架阴影设计

c# - 如何使用 XAML 和 C# 根据其当前位置选择垂直 ListView 项目?

c# - FileIO.WriteTextAsync(file, text) 使用什么编码?