まぐらぼ

日々の雑記を書いています。

WPFでBitmapImageを表示する方法

次の三通りの方法があります。
a) 絶対パス
b) 相対パス UriKind.Relative
c) pack形式 https://msdn.microsoft.com/ja-jp/library/aa970069(v=vs.110).aspx

絶対パスは論外なので、とりあえず、(b)を使っとけばよさそうです。
なお、ストアアプリ/UWPの場合、「img.Source = new BitmapImage(new Uri(@"ms-appx:///Images/sakura.png"));」です。

Image img = new Image();
idGrid.Children.Add(img);
try
{
//img.Source = new BitmapImage(new Uri(@"d:\temp\aaaa.png"));//絶対パス ...(a)
//! RelativeもOK
//img.Source = new BitmapImage(new Uri("/Images/sakura.png", UriKind.Relative)); ...(b)

//! pack形式 
img.Source = new BitmapImage(new Uri("pack://application:,,,/Images/sakura.png")); ...(C)
}
catch (Exception e){
Console.Write("{0}",e.ToString());
}

[XAML] で書く場合はこんな感じ。




サンプル [sample]download