Building a basic Silverlight slideshow using Microsoft Visual Studio 2008

In a recent assignment, I had to build a simple automatic Silverlight slideshow (wait 6 seconds for the image to change), and I had a hard time finding examples on the web, so I decided to write this simple tutorial to help those who want to develop a similar Silverlight slideshow application using Microsoft Visual Studio 2008. You can download the source code here: Silverlight Sildeshow.

Here is the example recompiled for Silverlight version 3, which is easily done by opening the project in Visual Studio 2008 with the proper Silverlight Tools version already installed.

Create a new project

First, you will need to download and install Microsoft Silverlight Tools Beta 2 for Visual Studio 2008. Once that is done, start Visual Studio and go to the File menu > New > Project (Ctrl + Shift + N).

Select Silverlight from the Project types, then Silverlight Application from the Templates.

New Project screenshot

In the next dialog box, select Dynamically generate an HTML test page to host Silverlight within this project and click Ok.

Visual Studio will then create the basic project files for you, here are the 4 main files : App.xaml, App.xaml.cs, Page.xaml, Page.xaml.cs.

screenshot 2

Details on main files

The App.xaml and App.xaml.cs files can be left untouched because this simple application does not need any resource scoped at the application level.

App.xaml is just an xml file loading 2 namespaces and defining which class represents the application.

App.xaml.cs defines 3 event handlers: Startup, Exit and UnhandledException.

In our case, the only one which is necessary is the Application_Startup, because it attaches a Page instance as the RootVisual (I think of it as a start page), we have no cleanup to perform in the Exit and exception handling is out of the scope of this article.

Building the structure

Page.xaml will define the structure of what we will see.

We will first set its Height and Width attributes to the desired dimensions:

<UserControl x:Class= »SilverlightSlideshow.Page »
xmlns= »http://schemas.microsoft.com/winfx/2006/xaml/presentation »
xmlns:x= »http://schemas.microsoft.com/winfx/2006/xaml »
Width= »411″ Height= »292″>

The grid element is the main container, and I will change its background color because I want to see it when I have no image:

<Grid x:Name= »LayoutRoot » Background= »#A4F546″>

You can add a background image like this :

<Grid x:Name= »LayoutRoot » Background= »#A4F546″>
<Image HorizontalAlignment= »Stretch » Margin= »0,0,0,0″ Source= »path/to/bg.jpg » Stretch= »Fill »/>

I added an image, which will have its source changed at a specified interval, and called it BigImage. The image has resources associated with it, its animations. The easiest way I found to set an interval was to create an animation that basically does nothing. The animation last for 6 seconds, and sets BigImage’s opacity from 1 to 1 (no change):

<Image x:Name= »BigImage »>
<Image.Resources>
<Storyboard x:Name= »WaitAnimation »>
<DoubleAnimation Duration= »00:00:6.00″ From= »1″ To= »1″
Storyboard.TargetProperty= »Opacity »
Storyboard.TargetName= »BigImage » />
</Storyboard>
</Image.Resources>

Coding

Let’s now add code in Page.xaml.cs to make this work. We need an array of strings to hold the list of image names and an integer variable which will contain the index of the currently displayed image in the array:

public partial class Page : UserControl
{
private string[] image_names;
private int current_index;

First way

I created a simple method to initialize the array, but you could get the filenames from an external xml file or a database:

private void GetImages()
{
image_names = new string[]
{
« images/photos-01.jpg »,
« images/photos-02.jpg »,
« images/photos-03.jpg »,
« images/photos-04.jpg »
};
}

Second way

And another method is to set the source of BigImage, using the image name array:

private void SetCurrentImage()
{
BigImage.SetValue(Image.SourceProperty, image_names[current_index]);
}

Now for the constructor :

public Page()
{
InitializeComponent();
GetImages();

current_index = 0;
SetCurrentImage();

Loaded += new RoutedEventHandler(Page_Loaded);
}

The mandatory InitializeComponent(); method is called, which initializes the underlying structure, then we initialize our name array, we set the current index to 0, we set the source of the image, and we attach an event handler to the Loaded event. Here is the event handler, which simply attaches the event handler for the Completed event of the animation, and starts the animation :

void Page_Loaded(object sender, RoutedEventArgs e)
{
Storyboard WaitAnim = (Storyboard)this.FindName(« WaitAnimation »);
WaitAnim.Completed += new EventHandler(WaitAnim_Completed);
WaitAnim.Begin();
}

The WaitAnim_Completed method changes the index and starts the animation again:

private void WaitAnim_Completed(object sender, EventArgs e)
{
current_index = current_index == image_names.Length – 1 ? 0 : current_index + 1;
Storyboard WaitAnim = (Storyboard)this.FindName(« WaitAnimation »);
SetCurrentImage();
WaitAnim.Begin();
}

Animation

The image source changes quite abruptly, we can add a fade transition using what we already know. First we have to add 2 more animations in the Page.xaml file, FadeInAnimation and FadeOutAnimation:

<Storyboard x:Name= »FadeOutAnimation »>
<DoubleAnimation Duration= »00:00:00.50″ From= »1″ To= »0″
Storyboard.TargetProperty= »Opacity »
Storyboard.TargetName= »BigImage » />
</Storyboard>
<Storyboard x:Name= »FadeInAnimation »>
<DoubleAnimation Duration= »00:00:00.50″ From= »0″ To= »1″
Storyboard.TargetProperty= »Opacity »
Storyboard.TargetName= »BigImage » />
</Storyboard>

The only difference between these 2 animations is the duration (half a second) and that they have a different From and To value, to really perform a change. 0 to 1 for FadeInAnimation and 1 to 0 for FadeOutAnimation.

Like we have done with WaitAnimation, we have to control the behaviour of their Page.xaml.cs.

We first have to attach the event handlers that will be called when the animations are completed, I have done so in the constructor:

Storyboard FadeOutAnim = (Storyboard)this.FindName(« FadeOutAnimation »);
FadeOutAnim.Completed += new EventHandler(FadeOutAnim_Completed);

Storyboard FadeInAnim = (Storyboard)this.FindName(« FadeInAnimation »);
FadeInAnim.Completed += new EventHandler(FadeInAnim_Completed);

I then defined the event handlers like so :

private void FadeInAnim_Completed(object sender, EventArgs e)
{
}

private void FadeOutAnim_Completed(object sender, EventArgs e)
{
}

We then have to change WaitAnim_Completed because the image has to fade out when the wait is over:

private void WaitAnim_Completed(object sender, EventArgs e)
{
Storyboard FadeOutAnim = (Storyboard)this.FindName(« FadeOutAnimation »);
FadeOutAnim.Begin();
}

Then, when the animation is completed, the image is invisible (opacity=0), we can change its source and start to fade the new image in. We make sure that current_index is not out of bounds and set it to 0 instead of incrementing it if it was equal to the highest index of the array (length of the array – 1):

private void FadeOutAnim_Completed(object sender, EventArgs e)
{
current_index = current_index == image_names.Length – 1 ? 0 : current_index + 1;
SetCurrentImage();

Storyboard FadeInAnim = (Storyboard)this.FindName(« FadeInAnimation »);
FadeInAnim.Begin();
}

Once the image has fully faded in, we start the wait animation again:

private void FadeInAnim_Completed(object sender, EventArgs e)
{
Storyboard WaitAnim = (Storyboard)this.FindName(« WaitAnimation »);
WaitAnim.Begin();
}

Whatever background color or image you have chosen will be visible during the fade in and fade out animations.

Since the first loaded image is always the same (« images/photos-01.jpg »), users might only see the same images even if you have several in your array. To overcome that issue, simply load the first image randomly by replacing :

current_index = 0;

with:

current_index = new Random().Next(0, image_names.Length – 1);

in the constructor in Page.xaml.cs

The generated html file is located in /Bin/Debug/TestPage.html, you can use that html to integrate your application in your website. Of course, this article showed a basic usage of Silverlight slideshow animations and can be greatly extended. It was just meant to provide a starting point.

Cette entrée a été publiée dans Création sites Internet. Vous pouvez la mettre en favoris avec ce permalien.

11 réponses à Building a basic Silverlight slideshow using Microsoft Visual Studio 2008

  1. Mani dit :

    Hai,

    Really this Slideshow is very simple and neat.
    In my vision, this is very nice than all example.

    thanks
    mani

  2. المحمل dit :

    I should be watching this Code
    Thank you very much

  3. Italiak1 dit :

    Thank you for valuable information.

  4. Angrish Ashwani dit :

    Very simple and usefull article.
    Thanx for this.
    A little mistake in the artice i.e

    private void WaitAnim_Completed(object sender, EventArgs e)
    {
    current_index = current_index == image_names.Length – 1 ? 0 : current_index + 1;
    Storyboard WaitAnim= (Storyboard)this.FindName(”WaitAnimAnimation”) ;////////////// In this Line MIstake
    SetCurrentImage();
    WaitAnim.Begin();
    }

    Solution for Mistake:
    change  » WaitAnimAnimation » to « WaitAnimation »

  5. Hi Angrish,

    Thanks for pointing that out. I’ve modified the article.

  6. Abbas dit :

    there appears to be some problem withthis… the setcauurentimage aint workin… its says u cant pass string as second param to SetValue()… hlp pls..

  7. Chanchal Ganotra dit :

    hey..

    Thanks alt.its really amazing.Its working absolutely perfect bt u myf face a problem in :

    BigImage.SetValue(Image.SourceProperty, image_names[current_index]);

    so the correction is:

    BitmapImage bmpImg2 = new BitmapImage();
    Uri uri2 = new Uri(image_names[current_index], UriKind.Relative);
    bmpImg2.UriSource = uri2;
    BigImage.Source = bmpImg2;

  8. Eduardo dit :

    Thanks for the great article ….

  9. Excellent job! I’m building my own slide show control as a SharePoint web part and this gave me a good head start.

  10. Nenukas dit :

    Excellent Job!!

  11. I agree, this is a great article.A successful blog needs unique, useful content that interests the readers

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>