Click here to Skip to main content
15,867,568 members
Articles / Desktop Programming / WPF
Article

WPF Slideshow

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
26 Mar 2012CPOL3 min read 63.8K   5.7K   18   3
This article demonstrates creating a slideshow in WPF.

Sample Image

Sample Image

Introduction

In this article, I have shown how to create a slide show in WPF. The main focus of this article is not on explaining any WPF concepts in-depth. Nor is it about any particular way of creating a slide show. Rather it explains how to integrate some of the features of WPF to create a simple application. The slide show application is extremely simple. In fact most people must be already familiar with the method of creating such an application. It uses a traditional approach of displaying a series of images sequentially on the click event of a button.

Background

The key concepts in WPF that I have used in my application are:

  • SolidColorBrush class
  • LinearGradientBrush class
  • RadialGradientBrush class
  • DispatcherTimer class
  • BitmapImage class

We will now look at each in detail.

  1. The SolidColorBrush class is the simplest type of brush. It uses a single color to paint a given area. It has a Color attribute to specify the color to be used.

    Following is the markup code for the SolidColorBrush:
  2. XML
    <Rectangle Width="70" Height="40">
      <Rectangle.Fill>
         <SolidColorBrush Color="Red"/>
      </Rectangle.Fill>
    </Rectangle>

    The output of the above code is as follows:

    Image 3

  3. The LinearGradientBrush class allows you to create a gradient effect using multiple colors. It has StartPoint and EndPoint attributes to specify where the color transition starts and ends. While specifying the StartPoint and EndPoint values, 0,0 represents the top left corner and 1,1 represents the bottom right corner. Each color is specified by using the GradientStop attribute with an Offset attribute.
  4. Following is the markup code for the LinearGradientBrush:

    XML
    <Rectangle Width="70" Height="40">
       <Rectangle.Fill>
          <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
             <GradientStop Color="Violet" Offset="0"/>
             <GradientStop Color="Indigo" Offset="0.2"/>
             <GradientStop Color="Blue" Offset="0.3"/>
             <GradientStop Color="Green" Offset="0.5"/>
             <GradientStop Color="Yellow" Offset="0.7"/>
             <GradientStop Color="Orange" Offset="0.8"/>
             <GradientStop Color="Red" Offset="1"/>
          </LinearGradientBrush>
       </Rectangle.Fill>
    </Rectangle>

    The output of the above code is the following rainbow colored gradient:

    Image 4

  5. The RadialGradientBrush class also allows you to create a gradient effect using multiple colors. However it creates an elliptical shaped gradient. Like the LinearGradientBrush class, each color is specified by using the GradientStop attribute with an Offset attribute.
  6. Following is the markup code for the RadialGradientBrush:

    XML
    <Rectangle Width="70" Height="40">
        <Rectangle.Fill>
           <RadialGradientBrush>
              <GradientStop Color="Violet" Offset="0"/>
              <GradientStop Color="Indigo" Offset="0.2"/>
              <GradientStop Color="Blue" Offset="0.3"/>
              <GradientStop Color="Green" Offset="0.5"/>
              <GradientStop Color="Yellow" Offset="0.7"/>
              <GradientStop Color="Orange" Offset="0.8"/>
              <GradientStop Color="Red" Offset="1"/>
           </RadialGradientBrush>
        </Rectangle.Fill>
    </Rectangle>

    The output of the above code is the following rainbow colored elliptical gradient:

    Image 5

  7. The DispatcherTimer class belongs to the System.Windows.Threading namespace. This class can be used to execute a particular piece of code at predefined intervals. It has an Interval property to specify this predefined interval. The Interval property takes an instance of the TimeSpan class as its value. The Tick event tells the timer which code must be executed by it.
  8. Following is the code to execute the timer_Tick function every two seconds:

    C#
    timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0, 0, 2);
    timer.Tick += new EventHandler(timer_Tick);
  9. The BitmapImage class is in the System.Windows.Media.Imaging namespace. The UriSource property of the BitmapImage class is used to specify the image file to be displayed on an Image control. The BitmapImage object is specified as the value of the Source property of the Image control.
  10. Following is the code to display the image.jpg file on an Image control:

    C#
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.UriSource = new Uri("image.jpg", UriKind.Relative);
    image.EndInit();
    myImage.Source = image;

Using the code

Following is the XAML code for the main window of the slideshow application:

XML
<Window x:Class="WPFSlideShow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
        Background="{StaticResource windowBrush}"
        Title="Slide Show" Height="391" Width="642">
    <Window.Resources>
        <SolidColorBrush x:Key="borderBrush" Color="Red"/>
        <LinearGradientBrush x:Key="firstBrush" StartPoint="0,0" EndPoint="1,1">
            <GradientStop Color="Red" Offset="0"/>
            <GradientStop Color="LightGreen" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="previousBrush" StartPoint="0,0" EndPoint="1,1">
            <GradientStop Color="LightGreen" Offset="0"/>
            <GradientStop Color="Red" Offset="0.4"/>
            <GradientStop Color="LightGreen" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="nextBrush" StartPoint="0,1" EndPoint="1,0">
            <GradientStop Color="LightGreen" Offset="0"/>
            <GradientStop Color="Red" Offset="0.4"/>
            <GradientStop Color="LightGreen" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="lastBrush" StartPoint="0,1" EndPoint="1,0">
            <GradientStop Color="LightGreen" Offset="0"/>
            <GradientStop Color="Red" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="progressBrush" StartPoint="0,1" EndPoint="1,1">
            <GradientStop Color="Violet" Offset="0.1"/>
            <GradientStop Color="Indigo" Offset="0.3"/>
            <GradientStop Color="Blue" Offset="0.4"/>
            <GradientStop Color="Green" Offset="0.5"/>
            <GradientStop Color="Yellow" Offset="0.7"/>
            <GradientStop Color="Orange" Offset="0.8"/>
            <GradientStop Color="Red" Offset="0.9"/>
        </LinearGradientBrush>
    </Window.Resources>
    <Canvas Width="595" Height="351">
        <Button Name="btnFirst" Background="{StaticResource firstBrush}" 
            BorderBrush="{StaticResource borderBrush}" Content="<<" 
            Canvas.Left="117" Canvas.Top="293" Width="60" Height="30" Click="btnFirst_Click" />
        <Button Name="btnPrevious" Background="{StaticResource previousBrush}" 
            BorderBrush="{StaticResource borderBrush}" Content="<" 
            Canvas.Left="183" Canvas.Top="293" Width="60" Height="30" Click="btnPrevious_Click" />
        <Button Name="btnNext" Background="{StaticResource nextBrush}" 
            BorderBrush="{StaticResource borderBrush}" Content=">" 
            Canvas.Left="249" Canvas.Top="293" Width="60" Height="30" Click="btnNext_Click" />
        <Button Name="btnLast" Background="{StaticResource lastBrush}" 
            BorderBrush="{StaticResource borderBrush}" Content=">>" 
            Canvas.Left="315" Canvas.Top="293" Width="60" Height="30" Click="btnLast_Click" />
        <ProgressBar Name="progressBar1" Background="{StaticResource progressBrush}" 
            BorderBrush="{StaticResource borderBrush}" Canvas.Left="115" 
            Canvas.Top="329" Height="10" Width="258" Minimum="1" Maximum="21" Value="1" />
        <CheckBox Name="chkAutoPlay" Canvas.Left="381" Canvas.Top="293" 
            Height="16" Width="117" Click="chkAutoPlay_Click">Play Automatically</CheckBox>
        <Image Canvas.Left="9" Canvas.Top="11" Height="275" x:Name="myImage" Stretch="Fill" Width="575"/>
    </Canvas>
</Window>

In the above code, I have created a SolidColorBrush resource named borderBrush for the border of buttons and four LinearGradientBrush resources named firstBrush, previousBrush, nextBrush, and lastBrush for the background of the buttons. Another LinearGradientBrush called progressBrush is created for the background of the progressbar control. I have used a RadialGradientBrush resource called windowBrush for the background of the main window. This resource is declared in the App.xaml file and its code is as follows:

XML
<Application x:Class="WPFSlideShow.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <RadialGradientBrush x:Key="windowBrush">
            <GradientStop Color="Pink" Offset="0.1"/>
            <GradientStop Color="LightGreen" Offset="0.2"/>
            <GradientStop Color="LightBlue" Offset="0.3"/>
            <GradientStop Color="LightYellow" Offset="0.4"/>
            <GradientStop Color="Pink" Offset="0.5"/>
            <GradientStop Color="LightGreen" Offset="0.6"/>
            <GradientStop Color="LightBlue" Offset="0.7"/>
            <GradientStop Color="LightYellow" Offset="0.8"/>
            <GradientStop Color="Pink" Offset="1.0"/>
        </RadialGradientBrush> 
    </Application.Resources>
</Application>

Following is the code for the MainWindow class:

C#
public partial class MainWindow : Window
{
    // Declaring a timer.
    DispatcherTimer timer;
    // counter to track images.
    int ctr = 0;
    public MainWindow()
    {
        InitializeComponent();
        // Initialize the timer.
        timer = new DispatcherTimer();
        // Specify timer interval.
        timer.Interval = new TimeSpan(0, 0, 2);
        // Specify timer event handler function.
        timer.Tick += new EventHandler(timer_Tick);
    }
    void timer_Tick(object sender, EventArgs e)
    {
        ctr++;
        if (ctr > 21)
        // Move to first image after last image.
        {
            ctr = 1;
        }
        PlaySlideShow(ctr);
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ctr = 1;
        PlaySlideShow(ctr);
    }
    private void PlaySlideShow(int ctr)
    // Function to display image.
    {
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        string filename = ((ctr < 10) ? "images/Plane0" + ctr + 
               ".jpeg" : "images/Plane" + ctr + ".jpeg");
               // Specify image file name in the Images folder in the application.
        image.UriSource = new Uri(filename, UriKind.Relative);
        image.EndInit();
        // Set image source.
        myImage.Source = image;
        // Specify stretch mode.
        myImage.Stretch = Stretch.Uniform;
        // Update progress bar.
        progressBar1.Value = ctr;
    }
    private void btnFirst_Click(object sender, RoutedEventArgs e)
    // Function to go to first image.
    {
        ctr = 1;
        PlaySlideShow(ctr);
    }

    private void btnPrevious_Click(object sender, RoutedEventArgs e)
    // Function to go to previous image
    {
        ctr--;
        if (ctr < 1)
        // Cycle to last image after first image.
        {
            ctr = 21;
        }
        PlaySlideShow(ctr);
    }

    private void btnNext_Click(object sender, RoutedEventArgs e)
    // Function to go to next image.
    {
        ctr++;
        if (ctr > 21)
        // Cycle to first image after last image.
        {
            ctr = 1;
        }
        PlaySlideShow(ctr);
    }

    private void btnLast_Click(object sender, RoutedEventArgs e)
    // Function to go to last image.
    {
        ctr = 21;
        PlaySlideShow(ctr);
    }
    private void chkAutoPlay_Click(object sender, RoutedEventArgs e)
    // Function to allow or disallow automatic slide show.
    {
        timer.IsEnabled = chkAutoPlay.IsChecked.Value;
        // Enable/Disable timer.
        // Show/Hide buttons.

        btnFirst.Visibility = 
          (btnFirst.IsVisible == true) ? Visibility.Hidden : Visibility.Visible;
        btnPrevious.Visibility = 
          (btnPrevious.IsVisible == true) ? Visibility.Hidden : Visibility.Visible;
        btnNext.Visibility = 
          (btnNext.IsVisible == true) ? Visibility.Hidden : Visibility.Visible;
        btnLast.Visibility = 
          (btnLast.IsVisible == true) ? Visibility.Hidden : Visibility.Visible;
    }
}

The above code allows a user to navigate between 21 images using first (<<), previous (<), next (>), and last (>>) buttons. The images are in the Images folder in the application. If the Play Automatically checkbox is selected, the buttons are hidden and the images are displayed in a sequence at an interval of two seconds.

Points of Interest

I have created this application using Visual C# 2010 Express Edition. With this article, I hope readers can understand the use of brushes, resources, the DispatcherTimer class, and the BitmapImage class in creating WPF applications.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
QuestionWPF Slideshow automatic Pin
Member 1515463715-Apr-21 22:44
Member 1515463715-Apr-21 22:44 
QuestionHow can i display the thumbnail view of the images in the listbox/listview horizontally... Pin
freakytrends20-Apr-12 2:59
freakytrends20-Apr-12 2:59 
AnswerRe: How can i display the thumbnail view of the images in the listbox/listview horizontally... Pin
Azim Zahir25-Apr-12 18:26
Azim Zahir25-Apr-12 18:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.