ImageSourceConverter - System.NullReferenceException

时间:2012-02-11 23:14:19

标签: wpf c#-4.0

我正在尝试加载一个外部XML文件,其中包含对WPF中图像的引用。

<page>   
    <foreground path="/data/images/attract/slide1/foreground.png">
    <background path="/data/images/attract/slide1/background.png">
</page>

我正在解析XML并使用以下代码将每个路径属性转换为ImageSource。

string backgroundString = (string)backgroundNode.Attributes["path"].Value;
Debug.WriteLine(backgroundString); //returns "/data/images/attract/slide1/background.png"
avm.BackgroundImage = new ImageSourceConverter().ConvertFromString(backgroundString) as ImageSource;

当我将它写入调试输出时,我正在解析的backgroundString不为null。但是,我收到以下错误。

A first chance exception of type 'System.NullReferenceException' occurred in PresentationCore.dll
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromString(String text)

有谁看到我做错了什么?任何帮助将不胜感激。

谢谢, 布赖恩

1 个答案:

答案 0 :(得分:5)

如果找不到该文件,则会出现该异常。首先,您应该在代码中使用BitmapImage,转换器用于XAML解析器。其次,相对路径将被解释为指向应用程序中的资源,如果不是这种情况,并且您希望指向相对于可执行文件的文件,则应该添加pack://siteoforigin:,,,(请参阅Pack URIs in WPF)。