Tuesday, July 7, 2009

Working with images in WPF is not straightforward

It's taken me a while to get my head wrapped around exactly what is going on here, but there's some serious issues with image controls in WPF.  My first manifestation of all this was that I'd load a BitmapSource into an Image, and it would not be visible, the control would continue to have a width and height of 0.  If I wrote code to try to manually set sizes ( even though I shouldn't have to ), the size of my image would come back as 0.  

What happens is, images are loaded on another thread.  So, when my code asks for the image size, it's 0.  Of course, this means if I am debugging, then I introduce a delay, so the thread can run, and the size is there.  So, if you want to do anything when an image is loaded, your best bet, is to use the size changed event on the Image control.  I've found that I need to put the images inside a StackPanel, if I put them in a Grid, they are just never visible, if I use the * notation, which I always try to do, to create forms that can be resized smoothly.  

What the framework desperately needs, is an ImageLoaded event, so you can write code to run when the image loads, THEN tell it to start loading.  I don't understand how this was missed, I'd have thought that being able to load an image, then do something based on the size of the image, would be pretty common in a framework whose main claim to fame is a freeform user interface.

No comments:

Post a Comment