兩步走:
1. 使用下面代碼制定文件路徑
"pack://application:,,,/AssembleName;component/Resources/Port3.png"
using System.Windows.Media.Imaging;//BitmapImage public BitmapImage UrlToImage(string path) { BitmapImage img = new BitmapImage(); try { img.BeginInit(); img.UriSource = new Uri(path); img.EndInit(); } catch (Exception ex) { System.Diagnostics.Debug.Print("UrlToImage:"+ex.Message); return null; } return img; } ... //主程序 //下面的AssembleName一般就是項目名稱,不帶任何后綴
//component是固定寫法 //下面的Resources是文件夾的名字,也可以叫Images或者Files string imgPath="pack://application:,,,/AssembleName;component/Resources/Port3.png" var imgShow=new Image(){Source=UrlToImage(imgPath)};
2. 設置圖片屬性
在項目瀏覽器中選中圖片,F4開屬性,Build Action設置成Resource,默認是Content

如果這步不做,就會持續收到報錯:“Cannot locate resource”
就這步我就搞了一下午。。。
REF:
https://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code
https://stackoverflow.com/questions/11948829/wpf-throws-cannot-locate-resource-exception-when-loading-the-image
