Click here to Skip to main content
15,867,594 members
Articles / Desktop Programming / XAML

Silverlight 2 Beta 2 - Using Animation for Sorting Image Items

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
9 Jul 2008CPOL2 min read 40K   544   19   3
Put image of products on the Canvas and drag and drop them to get them added to the cart. And use animation to sort them by id and price and recommend.
CartTest

Introduction

This is a simple Silverlight application to apply drag and drop shopping and use animation on sorting items.

Background

You need to have some Silverlight knowledge.

And some common sense to do computer programming. :)

Using the Code

You must install Silverlight 2 beta 2 tool to edit this project.

First of all, Product class is a template that contains all information for a product and Image object of the product and two DoubleAnimation objects for moving the Image object to the calculated point.

C#
public class Product
{
    public int ProductId
    {
        get;
        set;
    }
    public string ProductName
    {
        get;
        set;
    }
    public int ProductPrice
    {
        get;
        set;
    }
    public string ProductPhoto
    {
        get;
        set;
    }
    public int Recommend
    {
        get;
        set;
    }
    public Image ProductImage
    {
        get;
        set;
    }
    public DoubleAnimation MoveAnimationX
    {
        get;
        set;
    }
    public DoubleAnimation MoveAnimationY
    {
        get;
        set;
    }
    public Product(int productId, string productName, int productPrice, string productPhoto, int recommend)
    {
        this.ProductId = productId;
        this.ProductName = productName;
        this.ProductPrice = productPrice;
        this.ProductPhoto = productPhoto;
        this.Recommend = recommend;
    }
}

And Products class has static product list that has type of List<Product>.

C#
public class Products
{
    public static List<Product> products = new List<Product>();
    static Products()
    {
        products.Add(new Product(1, "Flower 1", 3000, "Flower (1).png", 4));
        products.Add(new Product(2, "Flower 2", 4000, "Flower (2).png", 1));
        products.Add(new Product(3, "Flower 3", 2500, "Flower (3).png", 2));
        products.Add(new Product(4, "Flower 4", 3600, "Flower (4).png", 8));
        products.Add(new Product(5, "Flower 5", 3000, "Flower (5).png", 5));
        products.Add(new Product(6, "Flower 6", 4000, "Flower (6).png", 2));
        products.Add(new Product(7, "Flower 7", 2500, "Flower (7).png", 3));
        products.Add(new Product(8, "Flower 8", 3600, "Flower (8).png", 1));
    }        
}

And all of the core logic is placed in Page.xaml.cs.

You can see that two DoubleAnimation XAML tags are in the <Canvas.Resource>.

Because of some change in Storyboard.SetTargetProperty() method that is not mentioned in MSDN, I couldn't use that method directly. So, I declared those properties on the resource (moveAnimationX, moveAnimationY) and used them like below:

Storyboard.SetTargetProperty(product.MoveAnimationX, 
	Storyboard.GetTargetProperty(moveAnimationX));
Storyboard.SetTargetProperty(product.MoveAnimationY, 
	Storyboard.GetTargetProperty(moveAnimationY));

Next, put items on the canvas by their size, and put additional tooltip rectangle for showing a product's Id, price, recommend, etc.

And attach event handlers for drag and drop like below:

C#
private void AddEventHandler(FrameworkElement shape)
        {
            shape.MouseEnter += onMouseEnter;
            shape.MouseLeave += onMouseLeave;
            shape.MouseLeftButtonDown += onMouseLeftButtonDown;
            shape.MouseLeftButtonUp += onMouseLeftButtonUp;
            shape.MouseMove += onMouseMove;
        } 

In event handler methods, there's nothing special but to do hittest between Image object and Cart rectangle object. If hittest is positive, then add the Image object to cart list.

C#
IEnumerable<UIElement> shapes = shape.HitTest(new Rect
	(Canvas.GetLeft(Cart), Canvas.GetTop(Cart), 
	Cart.ActualWidth, Cart.ActualHeight));
if (shapes.Count<UIElement>() > 0)
{
    Cart_MouseLeftButtonUp(Cart, new MouseButtonEventArgs());
}

And you can see three buttons each for sort items by Id, price, recommend.

Sorting animation logic is simple. Save the original position of an item and calculate the new position that the item should be in. And set the values to DoubleAnimation's From and To property.

C#
product.MoveAnimationX.From = Canvas.GetLeft(product.ProductImage);
product.MoveAnimationY.From = Canvas.GetTop(product.ProductImage);
product.MoveAnimationX.To = accumulatedWidth;
product.MoveAnimationY.To = accumulatedHeight;

When setting of all of item is over, fire animation.

C#
moveStoryboard.Begin();

Finally, the way to sort is apply the sort algorithm to the item list itself by using List<>.Sort() method.

It's one of the methods that describes the sorting algorithm.

C#
private int SortById(Product x, Product y)
       {
           if (x == null)
           {
               if (y == null)
               {
                   // If x is null and y is null, they're
                   // equal.
                   return 0;
               }
               else
               {
                   // If x is null and y is not null, y
                   // is greater.
                   return -1;
               }
           }
           else
           {
               // If x is not null...
               //
               if (y == null)
               // ...and y is null, x is greater.
               {
                   return 1;
               }
               else
               {
                   // ...and y is not null, compare the
                   // lengths of the two strings.
                   //
                   int retval = x.ProductId.CompareTo
           (y.ProductId);//x.Length.CompareTo(y.Length);
                   if (retval != 0)
                   {
                       // If the strings are not of equal length,
                       // the longer string is greater.
                       //
                       return retval;
                   }
                   else
                   {
                       // If the strings are of equal length,
                       // sort them with ordinary string comparison.
                       //
                       return x.ProductId.CompareTo(y.ProductId);
                   }
               }
           }
       }

And it's the button event handler that applies sorting algorithm to the item list itself.

C#
private void SortById_Click(object sender, RoutedEventArgs e)
        {
            //moveStoryboard.Begin();
            Products.products.Sort(SortById);
            LoadProducts();            
        }

The CanvasInitialized variable is used to indicate whether the main canvas is initialized or not.

At first, LoadProducts() method loads items to the canvas.

Secondly, LoadProducts() method sorts items by condition.

I know it's not a good article. :)

But I hope this helps.

Points of Interest

It was study for my work.

I'm trying to develop some food management and recipe community web site.

History

  • 9th July, 2008: Initial post

License

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


Written By
Web Developer
Korea (Republic of) Korea (Republic of)
I'm a super-elementary programmer.
I live in Suwon, Republic of Korea.
And i'm not very good at English.
hahaha!!!

Comments and Discussions

 
GeneralGetting Few Errors Pin
rowdykuttan15-Nov-08 22:25
rowdykuttan15-Nov-08 22:25 
GeneralRe: Getting Few Errors Pin
Mr.Darcy16-Nov-08 1:32
Mr.Darcy16-Nov-08 1:32 
This post is based on Silverlight 2 beta 2.
Now the Silverlight 2 RTW came out.
There is some breaking changes and you can check that out in the release document.

First of all, HitTest is moved to another class. So, you should fix that code like below,
//do hit test to find objects on the cart.
IEnumerable<UIElement> shapes = VisualTreeHelper.FindElementsInHostCoordinates(
new Rect(Canvas.GetLeft(Cart), Canvas.GetTop(Cart) + mainCanvas.ActualHeight + ddlStackPanel.ActualHeight, Cart.ActualWidth, Cart.ActualHeight)
, shape);

if (shapes.Count<UIElement>() > 0)
{
Cart_MouseEnter(Cart, e);
}

and about MouseEventArgs,
pass the argument like below,

Cart_MouseLeave(Cart, e);


If you wanna see full source code,
Check (http://www.codeproject.com/KB/silverlight/Silverlight_2_with_others.aspx[my recent post].

Haha. I'm a super-elementary programmer!!

GeneralRe: Getting Few Errors Pin
rowdykuttan16-Nov-08 5:50
rowdykuttan16-Nov-08 5:50 

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.