I just needed to add a simple image to my Silverlight application to include a company logo. Three hours later …
This post provides information on the image formats supported by Silverlight so that you don't run into the same issues and waste as much time as I did today.
[NOTE: To anyone on the Silverlight team that may read this: Why not have Visual Studio (or even Expression Blend) tell me I was making this mistake instead of letting me waste so much time!!]
First, I followed the *very* simple instructions I found everywhere:
1) Add the image to the Silverlight project.
I put mine in an Images folder in the project.
2) Set the Build Action for the image to "Resource".
3) Add the image tag to the XAML.
Easy peasy. Then why didn't it work? No image appeared. I read/tried everything I could think of but no luck. Three hours later my partner suggested I try another file… AND IT WORKED.
The problem was the image format!
- bmp: NOT SUPPORTED IN SILVERLIGHT
No warning, no error, it just does not display the image
- jpg: It works, but does not support a transparent color
- gif: It supports a transparent color, but NOT SUPPORTED IN SILVERLIGHT
- png: It works AND it supports a transparent color
As soon as I replaced my logo.bmp with a logo.png, it worked!
[For help setting up a transparent color, see this Silverlight Tip of the Day.]
So here again are the steps for adding an image to a Silverlight application:
1) Add the image to the Silverlight project.
BE SURE that the file is either a .jpg or .png format image.
NOTE: The above screen shot shows the image under my Silverlight VB project, but the same is true for a C# Silverlight project.
2) Set the Build Action for the image to "Resource".
3) Add the image tag to the XAML.
<StackPanel Background="BlanchedAlmond">
<Image Source="Images/Logo.png" Width="100"
HorizontalAlignment="Left"
Margin="2"/>
<data:DataGrid x:Name="CustomerList"
ItemsSource="{Binding Data, ElementName=CustomerSource}">
</data:DataGrid>
</StackPanel>
NOTE: Since I set up the file as a resource, I set the source property of the Image tag directly to the location of the image in the Silverlight project.
And the result:
Enjoy!