如何在Wpf中设置图像的来源?

时间:2013-10-09 08:51:55

标签: wpf

// Create the image element.
Image simpleImage = new Image();    
simpleImage.Width = 100;
simpleImage.Margin = new Thickness(5);

// Create source.
BitmapImage bi = new BitmapImage();

我应该如何将simpleImage的Source设置为bi?

2 个答案:

答案 0 :(得分:2)

// Create the image element.
Image simpleImage = new Image();    
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);

// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/Images/1.jpg",UriKind.RelativeOrAbsolute);

bi.EndInit();
// Set the image source.
simpleImage.Source = bi;

答案 1 :(得分:2)

var uri = new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg");
var bi = new BitmapImage(uri);
simpleImage.Source = bi;