Tutorials » Silverlight tutorials »

How to set a background image for your Silverlight control


This tutorial shows how to set a background image for the Silverlight controls using an ImageBrush element.


In Silverlight, the ImageBrush element can be used to fill an area with an image. The area could be various shape elements or the entire Canvas itself.

This code sample shows how to use the ImageBrush to set a background image for the Silverlight canvas control.

<Canvas x:Name="SnowCanvas" Width="600" Height="480">
<Canvas.Background>
<ImageBrush x:Name="backgroundImageBrush"
Stretch="UniformToFill"
ImageSource="Images/Background.png">
</ImageBrush>
</Canvas.Background>
</Canvas>



The below example shows how to Fill an ellipse area with an image control. In addition, I am using the Mouse Enter and Mouse Leave events to dynamically change the image used to fill the Ellipse shape.

<Ellipse x:Name="ellipse1"
MouseEnter="ellipse1_MouseEnter"
MouseLeave="ellipse1_MouseLeave"
Width="100"
Height="100">
<Ellipse.Fill>
<ImageBrush x:Name="imageBrush1"
Stretch="UniformToFill"
ImageSource="Images/Flower2.png">
</ImageBrush>
</Ellipse.Fill>
</Ellipse>

Here is the C# code to handle the Mouse Enter and Mouse Leave events and dynamically change the image in these events:

private void ellipse1_MouseEnter(object sender, MouseEventArgs e)
{
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"Images/Flower1.png", UriKind.Relative)); ;
ellipse1.Fill = brush;
}

private void ellipse1_MouseLeave(object sender, MouseEventArgs e)
{
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"Images/Flower2.png", UriKind.Relative)); ;
ellipse1.Fill = brush;
}





Next Chapter: Javascript to detect if Silverlight is installed
Previous Chapter: Silverlight databinding examples: BindingMode Enumeration
More Chapters: Silverlight Tutorials
More Tutorials: Tutorial Index


Subscribe to Subscribers
Awards & Gifts
Talk to Webmaster Tony John
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India