Горизонтальная карусель Silverlight для миниатюр? - PullRequest
0 голосов
/ 16 сентября 2010

UPDATE:

Я нашел это решение ... изменил его, но изо всех сил пытаюсь заставить его делать непрерывный цикл (1-й элемент появляется в списке / массиве до последнего)

Любая помощь очень ценится!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Browser;

/*
*   A Image Carousel Demonstratoin in C#
*   from shinedraw.com
*/

namespace ImageCarousel
{
public partial class ImageCarousel : UserControl
{

    private String[] IMAGES = { "images/image1.png", "images/image2.png", "images/image3.png", "images/image4.png", "images/image5.png", "images/image6.png", "images/image7.png", "images/image8.png", "images/image9.png"};    // images
    private static double IMAGE_WIDTH = 128;        // Image Width
    private static double IMAGE_HEIGHT = 128;       // Image Height        
    private static double SPRINESS = 0.4;           // Control the Spring Speed
    private static double DECAY = 0.5;              // Control the bounce Speed
    private static double SCALE_DOWN_FACTOR = 0.05;  // Scale between images
    private static double OFFSET_FACTOR = 50;      // Distance between images
    private static double OPACITY_DOWN_FACTOR = 0.1;    // Alpha between images
    private static double MAX_SCALE = 1;            // Maximum Scale


    private double _xCenter;
    private double _yCenter;

    private double _target = 0;     // Target moving position
    private double _current  = 0;   // Current position
    private double _spring = 0;     // Temp used to store last moving 
    private List<Image> _images  = new List<Image>();   // Store the added images

    private static int FPS = 24;                // fps of the on enter frame event
    private DispatcherTimer _timer = new DispatcherTimer(); // on enter frame simulator

    public ImageCarousel()
    {
        InitializeComponent();

        // Save the center position
        //_xCenter = Width / 2;
        //_yCenter = Height / 2;
        _xCenter = 0;
        _yCenter = Height / 2;

        addImages();

        // add the click handler
        this.MouseLeftButtonDown += new MouseButtonEventHandler(ImageNaigation_MouseLeftButtonDown);

        // add the scroll handler
        HtmlPage.Window.AttachEvent("DOMMouseScroll", OnMouseWheel);
        HtmlPage.Window.AttachEvent("onmousewheel", OnMouseWheel);
        HtmlPage.Document.AttachEvent("onmousewheel", OnMouseWheel);
    }



    /////////////////////////////////////////////////////        
    // Handlers 
    /////////////////////////////////////////////////////   

    // reposition the images
    void _timer_Tick(object sender, EventArgs e)
    {
        for(int i = 0; i < _images.Count; i++){
            Image image = _images[i];
            posImage(image, i);
        }


        // compute the current position
        // added spring effect
        _spring = (_target - _current) * SPRINESS + _spring * DECAY;
        _current += _spring;
    }

    // define the new target by mouse wheel
    private void OnMouseWheel(object sender, HtmlEventArgs args)
    {

        double mouseDelta = 0;
        ScriptObject e = args.EventObject;
        // Mozilla and Safari    
        if (e.GetProperty("detail") != null)
        {
            mouseDelta = ((double)e.GetProperty("detail"));
        }

        // IE and Opera   
        else if (e.GetProperty("wheelDelta") != null)
            mouseDelta = ((double)e.GetProperty("wheelDelta"));

        mouseDelta = Math.Sign(mouseDelta);

        moveIndex((mouseDelta > 0) ? 1 : -1);
    }


    // define the new target by mouse click (Forward position only)
    void  ImageNaigation_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        moveIndex(1);
    }

    /////////////////////////////////////////////////////        
    // Private Methods 
    /////////////////////////////////////////////////////   


    // add images to the stage
    private void addImages(){
        for(int i = 0; i < IMAGES.Length; i++){
            // get the image resources from the xap
            string url = IMAGES[i];
            Image image = new Image();
            image.Source = new BitmapImage(new Uri(url, UriKind.Relative));

            // add and reposition the image
            LayoutRoot.Children.Add(image);
            posImage(image, i);
            _images.Add(image);
        }
    }



    // move the index
    private void moveIndex(int value)
    {
        _target += value;
        _target = Math.Max(0, _target);
        _target = Math.Min(_images.Count - 1, _target);
    }

    // reposition the image
    private void posImage(Image image , int index){
        double diffFactor = index - _current;


        double left = _xCenter + ((IMAGE_WIDTH + OFFSET_FACTOR) * diffFactor);
        double top = _yCenter;


        image.SetValue(Canvas.LeftProperty, left);
        image.SetValue(Canvas.TopProperty, top);

    }

    /////////////////////////////////////////////////////        
    // Public Methods
    /////////////////////////////////////////////////////   

    // start the timer
    public void Start()
    {
        // start the enter frame event
        _timer = new DispatcherTime`enter code here`r();
        _timer.Interval = new TimeSpan(0, 0, 0, 0, 1000 / FPS);
        _timer.Tick += new EventHandler(_timer_Tick);
        _timer.Start();
    }
}
}

1 Ответ

0 голосов
/ 16 сентября 2010

сколько элементов у вас в списке?

Один из очень простых подходов - создать список на вашей странице, скажем, с шириной 600 пикселей.Затем оберните его в холст, у которого свойство clipToBounds имеет значение true, а его ширина меньше значения списка, скажем 300px.

Затем добавьте кнопки слева и справа от холста, и когдаВы щелкаете по ним, вы можете установить RenderTransform поля списка как TranslateTransform, и сместить его влево на X пикселей (на самом деле, анимация была бы лучше, с более плавным скользящим движением) влево или вправо (с проверкой некоторых очевидных границ).

HTH

PS Причина, по которой я спросил, сколько предметов, заключается в том, что если у вас есть сотни предметов, вам может потребоваться динамическая загрузка ваших предметов или виртуализация списка, что изменится.вещей немного.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...