2012-02-11 53 views
0

我想加載一個外部XML文件,其中包含對WPF中圖像的引用。ImageSourceConverter - System.NullReferenceException

<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不爲空。但是,我收到以下錯誤。

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) 

有沒有人看到我在做什麼錯了?任何幫助將非常感激。

感謝, 布萊恩

回答

3

你得到異常,如果沒有被發現的文件。首先,您應該在代碼中使用BitmapImage,轉換器用於XAML分析器。其次,相對路徑將被解釋爲指向應用程序中的資源,如果不是這種情況,並且您希望指向與可執行文件相關的文件,則應該預先配置pack://siteoforigin:,,,(請參閱Pack URIs in WPF)。

相關問題