Click here to Skip to main content
Email Password   helpLost your password?
screen capture

Introduction and Background

What is Carousel? Carousel is just a Silverlight 2.0 (now it's has been updated to Silverlight v3) control which can display collections of pictures like a carousel (have you ever see a carousel?). When I creating Mashup in Microsoft Popfly I saw a display control named "Carousel." It was very attractive to me so I wanted to find one like this to use it in my own application. Using Google I found YetAnotherCarousel, but it was too coarse to use. And the other one I found was created in Silverlight V1 and was very hard to use. But the idea dogged me, attracted me day and night. I Googled again and again but could not find a perfect one. So one day, I asked myself, "Why not create one for myself?"

Key Features

Using the Control

Using the Carousel control is very simple just like any other control. First of all, you add the assembly (cokkiy.display.carousel) and reference it to your Silverlight Project. Then look at the code:

  1. Add the XMLNS reference to your Page XAML file beginning.
    <UserControl x:Class="ControlTest.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:display="clr-namespace:Cokkiy.Display;assembly=Cokkiy.Display.Carousel"
                 Width="800" Height="600">
  2. Place the Carousel in your layout control. I put it in a grid, and you can put it in any UIElement as a content or child item.
    <display:Carousel x:Name="carousel" TurnDirection="Counterclockwise"
          Padding="5,5,5,5" >
                <display:Carousel.Background>
                    <LinearGradientBrush EndPoint="0.5,0" StartPoint="0.5,1">
                        <GradientStop Color="#FF000000"/>
                        <GradientStop Color="#FFFFFFFF" Offset="1"/>
    
                    </LinearGradientBrush>
                </display:Carousel.Background>
                <display:Carousel.ItemSources>
                    <display:ItemSource Title="01" ImageSource="Images/01.jpg"/>
                    <display:ItemSource Title="02" ImageSource="Images/02.jpg"/>
                    <display:ItemSource Title="03" ImageSource="Images/03.jpg"/>
    
                    <display:ItemSource Title="04" ImageSource="Images/04.jpg"/>
                    <display:ItemSource Title="05" ImageSource="Images/05.jpg"/>
                    <display:ItemSource Title="06" ImageSource="Images/06.jpg"/>
                    <display:ItemSource Title="07" ImageSource="Images/07.jpg"/>
                    <display:ItemSource Title="08" ImageSource="Images/08.jpg"/>
                </display:Carousel.ItemSources>
    
            </display:Carousel>

The ImageSource property just is the Silverlight Image's source, so you can set it any valid Url as Image's source do, more info about it you can refer MSDN's Image's source property.

Notice how I added a Carousel in my page. The Carousel has 8 images as its children. Let's look at the screen capture.

Screen capture

How It Works?

From the screen capture we can know the Carousel is composed of three main parts. The Canvas where the image placed, the small item (the carousel leaf) contains an image which can turn around with the ellipse (it is a virtual image ellipse does not exist) and the panel displays the selected image (the large image in the picture). All three parts are also Silverlight controls which have their own properties. The carousel leaf control I called is CarouselItem which calculates the position of where to place the Canvas, and the scale range by itself. The key point is in placing each item in a proper point and making its size fit any position, and making it turn along with the ellipse.

To make the Carousel control like a real carousel, we must ensure:

Let's see the following figure demo the concept.

carousel figure

When the center point, O, is constant, the positon and size of CarouselItem at point P only depends to the angle of A. We can calc the positon and size like following code.

    // Position 
    double dx = Axis.Width * Math.Cos(newAngle) + Center.X; 
    double dy = Axis.Height * Math.Sin(newAngle) + Center.Y; 
    Canvas.SetLeft(this, dx);
    Canvas.SetTop(this, dy); 
    // Scale 
    double sc = 2 + Math.Cos(newAngle - Math.PI / 2); 
    ScaleTransform st = (
        this.RenderTransform as TransformGroup).Children[0] as ScaleTransform; 
    st.ScaleX = sc; 
    st.ScaleY = sc; 
    // Set the ZIndex based the distance from us, the far item 
    // is under the near item 
    Canvas.SetZIndex(this, (int)dy);

The position and size all only depends on the angle, so it's very easy to make it turn around the ellipse. Silverlight support the DependencyProperty animation, so we make the angle as a DependencyProperty. And make a DoubleAnimation on each item's angle property. The DoubleAnimation has a property named By which means the total amount by which the animation changes its starting value. When we set it to 2*PI, it starts turning a lap.

    Storyboard storyboard = new Storyboard();
    //this.Resources.Add(name, storyboard);

    // Angle animation
    DoubleAnimation doubleAnimation = new DoubleAnimation();
    doubleAnimation.By = 2*Math.PI;
    doubleAnimation.Duration = duration;
    doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

    // Set storyboard target property
    storyboard.Children.Add(doubleAnimation);
    Storyboard.SetTarget(doubleAnimation, item);
    Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("Angle"));

We create a storyboard for each item and then add all these storyboards to a global storyboard. Then if we want the carousel to turn, we just start the global storyboard.

History

My English is not very good so I hope you can understand what I've said. The sample code  include some pictures from public web, you should not use the image in your product.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGreat Job in Silverlight. deserve 5 rate'G.
santosh d
1:59 3 Mar '10  
Thanks for posting this project it will more helpfull. So i rate Excellent.
QuestionGreat Article
rgturner
18:40 31 Jan '10  
This is a great article. One question. Can this be done using Visual Basic 2008? Do you have a Visual Basic 2008 version?
GeneralStart in Full Screen
arkalum
6:37 19 Jan '10  
How can i make the carrousel start in Full screen ?

Thanks for answering
GeneralThe page is blank from second time run
madhanprabu
20:36 8 Nov '09  
Hi,

Thank you for the nice work.
when i run your code first time its successfully runs and i see the control working, from the second time onwards the page is blank and sometimes i get out of memory exception even i have 2.5 GB free space on c drive and 10GB space on D drive.
I am new to silverlight and please give me the solution for this.

Thanks/Regards,
Madhan Prabu
GeneralRe: The page is blank from second time run
cokkiy
1:12 10 Nov '09  
Hi,
Can you describe what you doing more detail or if it appropriate you can send me a copy of your code.

The God created the world.
The programer made the world easy.

GeneralReplacing Uri (ImageSource) with Memorystream
FLIron
5:47 16 Oct '09  
Hello,

First, a big bravo for your control, it's a great great job !

I included it in a silverlight 3 solution. As my images are dispatched in differents hard drives in the server, I dynamically copy them in a directory which is at the same place than the xap file. For that I created a Web Service (dot net) which make the copies. So each carousel item is created with a good uri. I then modified the mouse left button event of the ItemViewerControl (in your code it makes the ItemViewerControl disappear), so that the click on a ItemViewerControl dynamically displays a popup that shows my image in a bigger format. Everything is good except that there is no progress bar when silverlight download in the client cache the images. So when they are a little big, the carousel shows empty rectangles until the first images are downloaded.
To avoid this, I modified the Source property. Instead of an Uri, I tried to put a Memorystream. The bitmap is not created by the Uri, but by the MemoryStream.
The big advantage doing this is that I can download my images by web service (and then display a progress bar if I download them by blocks). After each download, I add the carousel item which displays them very well. My problem is the following : when I click on a carousel item (the little cycling image) the big image (which grows up by a story board) doesn't appear... But the title normally appears when the mouse enters in it. So the ItemViewer is here, but not my image. I put break point at each instruction who speak about ImageSource (Wink ), but the value is a bitmap each time. More, when I click on the title, the popup I created myself opens, and the biggest image is here !!! I don't understand what's happening, and why my image is not displayed in the ItemViewerControl.
I search in your code (I don't understand the whole, I admit), and I can't find the control which is used to display the image. Is this an image, a bitmap, a rectangle, something else ? Where do you do that ?
If you can help me, it would be very nice.
Sorry if my post is too long !

FLIron
GeneralRe: Replacing Uri (ImageSource) with Memorystream
cokkiy
6:48 16 Oct '09  
Hi, the ItemViewerControl contains an Image control to display the larger picture, yan can find this in generic.xaml file. So I thinks if you just change the Uri to Memorystrem and properly created the ItemSource's ImageSource property, the larger picture should appear.
If you still have this problem, maybe you can add a Memorytream property in ItemSource and then in item_MouseLeftButtonDown method recreate a ImageSource using the memorystream and then apply it to SelectedItemViewer.Source.

The God created the world.
The programer made the world easy.

GeneralRe: Replacing Uri (ImageSource) with Memorystream
FLIron
11:15 16 Oct '09  
Hi !

Thanks for your answer ! I will try to create a MemoryStream property, I hope it will work !
I'll tell you if it does.
See you later !

Bye
FLIron
GeneralRe: Replacing Uri (ImageSource) with Memorystream
FLIron
3:04 19 Oct '09  
Hello !

I did what you suggested (adding MemoryStream as a property, and all is fine !
Thanks for your answer and , again, a big applause for your control !

See you

FLIron
Generalcarousel problem value does not fall within the expected range
Priyanka Katare
21:42 21 Sep '09  
when i redirect from one page to the page which ia having carousel control
then it shows the same problem
Can any one help me on this
GeneralRe: carousel problem value does not fall within the expected range
cokkiy
1:17 10 Nov '09  
Hi,
What's problem are you encounter? Can you describe it more detail?

The God created the world.
The programer made the world easy.

GeneralHyperlink Images
MMRR
12:11 18 Sep '09  
Hello,

Can the images be hyperlinked and open webpages in a new window?

By the way, it is a great sample!
GeneralRe: Hyperlink Images
Xel3
10:59 19 Dec '09  
I'd be very interested in how to pass a hyperlink along with the images as well! I'd like the user to get a new tab pop up with the link attached to the current picture when the big currently selected picture is clicked.

Is there anybody that can modify the code for this???
GeneralRe: Hyperlink Images
cokkiy
19:49 19 Dec '09  
Hi, It's very simple. You just need rewrite the
void _selectedItemViewer_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
SelectedItemViewer.Source = null;
// Please add Navigator code here
// Something like this:
// HtmlPage.Window.Navigate(uri);
}
function in Carousel.cs file.

You can add a property to ItemSource class represents the url that you want the user navigate to. So you can get this url in the _selectedItemViewer_MouseLeftButtonUp method like this:
string url =SelectedItemViewer.Source.your-property-name

The God created the world.
The programer made the world easy.

GeneralExcellent job
wguerram
5:49 14 Sep '09  
Cokkiy, You have done an excellent job.

Congratulations.
GeneralMy vote of 1
VickyC#
13:47 16 Aug '09  
what is this?
GeneralRe: My vote of 1
santosh d
2:02 3 Mar '10  
have u ever post any project
GeneralAssemblycokkiy.display.carousel not available
Member 3005364
22:31 7 Aug '09  
I could not find the assembly cokkiy.display.carousel
please let me know where i can download it.
GeneralRe: Assemblycokkiy.display.carousel not available
cokkiy
23:44 7 Aug '09  
You should compile the source code that you have been downloaded to get the assembly cokkiy.display.carousel

The God created the world.
The programer made the world easy.

QuestionThanks for your great Carousel. But I put this display:Carousel into one frame page, error happened when navigating back to this page.
paynechen
18:58 6 Aug '09  
The exception happened in Carousel->Items_CollectionChanged->case NotifyCollectionChangedAction.Add.
The problem is same as that one from Fernando A. Gomez F.

Do you have any suggestion?
I am using Silerlight 3Thumbs Up Thumbs Up
AnswerRe: Thanks for your great Carousel. But I put this display:Carousel into one frame page, error happened when navigating back to this page.
Azy2
17:11 21 Feb '10  
I am having the same problem with carousel and navigation, I am using silverlight business application template and in one of my navigation links i am using carousel, but when navigation back to this page, i'm getting error.
any idea how to resolve the issue?
GeneralWill u implement this Carousel in WPF as Panel
madhankumar.gi
21:10 2 Aug '09  
HI cookiy.....

i need the panel of the same type....

will u develop and send it to me....


mail id:maddhy@gmail.com
Generalabout chinese version
nicholas_pei
19:00 2 Aug '09  
Hi cokkiy,
Can you send me a chinese version?
Thanks.
GeneralI run projecto, but dont show carousel in page
Felipe Oliveira
5:08 30 Jul '09  
Hi,

I downloaded the code project and Run in Visual Studio, but after compile, in the page, dont show carousel, why?
Use Silverligth 2.0.

thanks
GeneralNice work, thanks - a little problemo though
Fernando A. Gomez F.
20:04 22 Jul '09  
Nice work, nice control. I'm new to Silverlight, and this control of yours helped me understand many things. It was of great aid.

I had this problem though. I put your control in a UserControl, and while the app is running, it creates several UserControl-derived classes. Whenever I created a new instance of the UC that had your control, it throwed me an ArgumentException. In particular, at Carousel.cs line 491, because both radiousY and radiousX variables where negative numbers (-45.0 actually) and the Size constructor can't have negative values. As a work around (and without actually deeply reviewing your code, I must confess) I did change lines 480 to 483 with these:

double radiusX = Math.Max((this.CarouselCanvas.ActualWidth - 2 * ItemWidth
- (Padding.Left + Padding.Right)) / 2, 0.0);
double radiusY = Math.Max((this.CarouselCanvas.ActualHeight - 2 * ItemHeight
- (Padding.Top + Padding.Bottom)) / 2, 0.0);

Simply, if either radius is negative, then default it to zero. And that worked for me.

However there was another problem: it duplicated the images (i.e. ItemSources) whenever a new instance of the UC was created. I guess it has something to do with the fact that Carousel.ItemSourceCollection is a dependency property and thus it refers to a static member. Perhaps the Carousel control is not cleaning the contents. As a work around, I simply called _carousel.ItemSources.Clear(); before leaving the page and that worked for me.

Well, hope this helps. Got my five.

Cheers.

Badger

Stupidity is an International Association - Enrique Jardiel Poncela


Last Updated 2 Aug 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010