2017-02-27 111 views
0

如何將ImageSource設置爲來自特定文件夾的圖像?從特定文件加載圖像

我試圖移動在調試圖像和運行下面的代碼:

image.Source = new BitmapImage(new Uri("kafpodhlato.png")); 

,但我得到了以下錯誤:

An unhandled exception of type 'System.UriFormatException' occurred in System.dll

Additional information: Invalid URI: The format of the URI could not be determined.

編輯:創建一個文件夾命名爲資源,設置它的Build actionResource然後使用下面的代碼解決了我的問題。

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/panamaxi.png")); 
+0

加載它? –

回答

3

這應該工作:

image.Source = new BitmapImage(new Uri("kafpodhlato.png", UriKind.Relative)); 

您可以但是要由Pack URI從裝配資源加載圖像。

將圖像文件添加到Visual Studio項目中,例如到名爲Images的文件夾。然後設置其Build ActionResource,並可能使用其他`Uri`構造函數通過

image.Source = new BitmapImage(new Uri("pack://application:,,,/Images/kafpodhlato.png")); 
+0

[MSDN鏈接](https://msdn.microsoft.com/zh-cn/library/ms131565)。 –

+0

試過了,沒有錯誤,但圖像不會加載...也許我必須更好地指定路徑?或者將圖像放在Debug中解決了這個問題? – ThP

+0

@ThP看我的編輯。你應該讓你的鏡像文件成爲一個程序集資源。 – Clemens