Search code examples
xamlwindows-phone-7windows-phone-8imagesourcebitmapsource

How to feed a custom ImageSource to Image in XAML


One way to set an ImageSource for Image in XAML is like this:

<Image Width="75" Height="75">
    <Image.Source>
        <BitmapImage UriSource={Binding Uri} DecodePixelWidth="75" DecodePixelHeight="75" />
    <Image.Source>
</Image>

This code contains a nice optimization, since a potentially large bitmap will be decoded to 75x75 pixels.

I'd like to be able to replace BitmapImage with my custom class like this:

<Image Width="75" Height="75">
    <Image.Source>
        <custom:PictureBitmap Picture={Binding Picture} Width="75" Height="75" />
    <Image.Source>
</Image>

My application implements the Picture class, which maps to a database table. Picture class has everything I need to create an instance of BitmapImage. So PictureBitmap is essentially an adapter for the BitmapImage.

Here is how I started:

public class PictureBitmap : BitmapSource
{
    // TODO: create Picture Dependency Property
    // TODO: create a BitmapImage from Picture
    // TODO: implement abstract methods by delegating calls to BitmapImage
}

Although BitmapSource is abstract, the API reference doesn't explain how to implement it.

Does anyone know how to feed a custom object to Image.Source?

My app supports Windows Phone Mango (7.5) and up.

Thanks!


Solution

  • Solved the problem by taking the attached properties approach.

    To set the Source property on an Image using my custom logic, I do the following:

    <Image Width="75" Height="75" my-namespace:PictureBitmap.Source={Binding Picture} />
    

    This link turned out to be tremendously helpful: https://stackoverflow.com/a/16103494/1809457

    Also, I noticed that DecodePixelWidth and DecodePixelHeight properties were not available in Mango.

    Mango Provides the PictureDecoder class, however the drawback is that it must be used on the UI thread.