My scenario is the following. I am creating a little math quiz application for my son and wanted to dynamically change the background ImageBrush of my canvas after each question is answered. I proceeded to embed my images (pngs) into a resource file and figured I would load them into an array and then randomly choose one and load it into the canvas.
The first problem I ran into was of course the fact that in the resource file the images were being stored as Bitmaps. So after some looking around on the Internet I finally figured out how to get them converted from Bitmap to BitmapImage objects using the following helper method:
private BitmapImage FromResourceBitmap(Bitmap bitmap)
{
var result = new BitmapImage();
using(var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
stream.Position = 0;
result.BeginInit();
result.StreamSource = stream;
result.EndInit();
}
return result;
}
From there I created an ImageBrush from the BitmapImage and assigned it to the Background property of the canvas:
var brush = new ImageBrush {ImageSource = m_Media.Screens[0]}; // m_Media.Screens[x] returns a BitmapImage...obviously.
QuestionCanvas.Background = brush;
Unfortunately, this doesn't seem to work. When the application runs the background is pure white. My XAML doesn't describe any backgrounds and...well I'm confused. Any help would be greatly appreciated! Thank you!