What is the property type the Image control will bind to in Silverlight?

Mar 6, 2011 at 5:51 PM

I have an <Image x:Name="Avatar"> control on my View.

The following on my ViewModel: public Image Avatar { get; set; }

This property always NULL.

I've tried the "Image", "ImageSource", BitmapSource.  Any other ideas?  What is the default binding for the Image?


Mar 6, 2011 at 6:49 PM

The default property for Image is Source. If you are ever unsure of what the defaults are, you can check them in the ConventionManager.

Mar 7, 2011 at 4:22 AM

I may be wasn't clear enough - what should be type of the VM property?  I knew that the Source is the default one, but I can't find an appropriate type match on my VM - I think this is why the binding doesn't occur.

Bottom line - what should be a property definition on the VM to ensure correct binding of the Image control to my VM?


Mar 7, 2011 at 7:26 AM

I would bind it to a URI. The default ImageSourceTypeConverter is able to handle the URI -> ImageSource convention, given that the URI points to a valid resource (it not, the TypeConverter will throw an exception). I found the URI definition to be more suitable for a VM.

Mar 9, 2011 at 5:05 PM

Are you saying that if the image is built in memory there is no way to bind to it? Unless I create an in-memory service that can serve the images by URLs?

Mar 9, 2011 at 5:31 PM

No, I am saying that in my view-models I am using URIs to address images that are part of an assembly (icons that are used for buttons, backgrounds etc.), and that I prefer to decouple view-model and view as much as I can.

If the image is generated dynamically, you have a lot of options, depending on how much you want to decouple the view-model from the view:

  • As you are suggesting, a possible way is to create a service that acts as a bridge between the actual ImageSource and the view-model-side representation (e.g. a Guid, a string...).
  • Another possible way is to expose the source as an ImageSource, at the cost of having a WPF-dependant view-model, or a byte[], leaving to the view the responsability to display the image properly.
  • Another solution would be to expose the service used to generate the image itself, and let the UI request the ImageSource generation when needed.

You can use whatever solution fits your scenario better, but do not try to use conventions at all costs: they can be useful and of course speed up work, but there are always cases where your view has to be properly tailored.