ImageSourceConverter - System.NullReferenceException


February 2019


2.8k time


I'm trying to load an external XML file that contains references to images in WPF.

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

I'm parsing the XML and using the following code to convert each path attribute to an 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;

The backgroundString I'm parsing is not null when I write it to the debug output. However, I'm getting the following error.

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)

Does anyone see what I'm doing wrong? Any help would be much appreciated.

Thanks, Bryan

1 answers


You get that exception if the file is not being found. Firstly you should use a BitmapImage in code, the converters are for the XAML-parser. Secondly relative paths will be interpreted as pointing to a resource in the application, if this is not the case and you want to point to files relative to the executable instead you should prepend pack://siteoforigin:,,, (see Pack URIs in WPF).