Rev
Rev

Reputation: 2265

Binding Bitmapimge to Image in Wpf?

This is a simple Question (lets see)

I want to bind bitmap image to Image. For doing this in cs code u must write this line.

this.leftImage.Source = new BitmapImage(new Uri(@"C:\a.bmp"));

But I want make Binding from resources. Because In release time resources became part of project.exe file and if you make binding from file(Mean set Image.source with Image file address), you must always put image file in the same address(disaster programing) :)

Upvotes: 1

Views: 2867

Answers (1)

Mike
Mike

Reputation: 204

One option is to get it from a resx file. You can do something similar to this. Assuming Images.resx contains a Left image bitmap.

leftImage.Source = ConvertBitmapToBitmapImage(Images.Left);
...
private BitmapImage ConvertBitmapToBitmapImage(Bitmap bitmap)
{
  MemoryStream memoryStream = new MemoryStream();
  bitmap.Save(memoryStream, ImageFormat.Png);
  BitmapImage bitmapImage = new BitmapImage();
  bitmapImage.BeginInit();
  bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
  bitmapImage.EndInit();

  return bitmapImage;
}

With some more work, you can do this from XAML too.

Upvotes: 2

Related Questions