Silverlight 4.0 Tutorial (11 of N): Roulette Behavior
You can find a list of the previous tutorial posts here
Continuing our RegistrationBooth Application…
In most of the offline events we hold, there are some giveaways for the audience (most of the time the prize is XBOX). Picking a winner is manual process where we collect the feedback forms, put it in a big box/bag, shake the box/bag and turn it upside down multiple times to make sure that the forms are scrambled enough so that when we pick a form it will be a random one , not the best process I know.
So in this post we will add to our RegistrationBooth application the ability to perform a random draw. we already have our attendees listed in a PathListBox, wouldn’t it be nice if this list can spin like a roulette till it stops at the lucky winner, let’s see how we can implement this. I thought it’s better if we implement this feature as a behavior so that we can easily apply it to any PathListBox, I will call this behavior RouletteBehavior.
To create a behavior we need to derive from the abstract class Bahavior<T> available in the System.Windows.Interactivity assembly, where T is the control or UI Element that you will attach this behavior to. in our case our behavior will derive from Bahavior<PathListBox>
- public class RouletteBehavior : Behavior<PathListBox>
- {
- }
What properties this behavior will expose? first there should be a way to start the roulette, for maximum usability we will add a property StartCommand of type ICommand, so that users of this behavior can use any type of trigger to start the roulette
- /// <summary>
- /// Gets a command that starts the roulette animation.
- /// </summary>
- public ICommand StartCommand
- {
- get;
- private set;
- }
We need another property to determine how long the roulette will spin, so we will add a property Duration of type Duration, I will make this property a DependencyProperty to make it open for any advanced scenario that the users of this behavior might want to implement.
- /// <summary>
- /// Gets or sets the approximate duration of the roulette.
- /// </summary>
- public Duration Duration
- {
- get { return (Duration)this.GetValue(RouletteBehavior.DurationProperty); }
- set { this.SetValue(RouletteBehavior.DurationProperty, value); }
- }
- public static readonly DependencyProperty DurationProperty =
- DependencyProperty.Register("Duration", typeof(Duration), typeof(RouletteBehavior),
- new PropertyMetadata(new Duration(new TimeSpan(0, 0, 1))));
To be able to customize the spinning speed we will expose a property called Speed (of type integer) that determines the speed of spinning it terms of items/second
- /// <summary>
- /// Gets or sets the speed of the roulette (Items/Sec).
- /// </summary>
- public int Speed
- {
- get { return (int)this.GetValue(RouletteBehavior.SpeedProperty); }
- set { this.SetValue(RouletteBehavior.SpeedProperty, value); }
- }
- public static readonly DependencyProperty SpeedProperty =
- DependencyProperty.Register("Speed", typeof(int), typeof(RouletteBehavior),
- new PropertyMetadata(5));
There are two protected method that we need to override, OnAttached and OnDetaching these methods are called when attaching and detaching the behavior to a PathListBox, the AssociatedObject property of the Behavior gives you access to the PathListBox you are attaching the behavior to, so what we do is we change the WrapItems property of the PathListBox when attaching the behavior and we set it back to the original value when detaching the behavior
- protected override void OnAttached()
- {
- base.OnAttached();
- _originalWrapItems = AssociatedObject.WrapItems;
- AssociatedObject.WrapItems = true;
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- AssociatedObject.WrapItems = _originalWrapItems;
- }
To create the spinning animation we will need a storyboard, so we will add a member variable of type Storyboard to our behavior class and in the constructor we will initialize the storyboard and attach a method called StartRoulette to the StartCommand
- public RouletteBehavior()
- {
- this.StartCommand = new ActionCommand(this.StartRoulette);
- this.rouletteAnimationStoryboard = new Storyboard();
- }
The StartRoulette method contains the logic for animating the PathListBox items, we do this by creating a DoubleAnimation to animate the Start property of the LayoutPath of the PathListBox (currently this behavior supports only one layout path), based on the list items count, the Speed property, the Duration and a generated random number we calculate the final value of the Start property that we will assign to the To property of the animation.
We assign a Circle out easing function to the animation so that the speed of spinning is decreased over the duration of the animation till it stops.
- private void StartRoulette()
- {
- PathListBox pathListBox = this.AssociatedObject as PathListBox;
- int itemsCount = pathListBox.Items.Count;
- if (pathListBox == null || pathListBox.Items == null || itemsCount <= 1)
- {
- return;
- }
- //Support one layout path only?
- PropertyPath propertyPath = new PropertyPath(String.Format("(ec:PathListBox.LayoutPaths)[{0}].(ec:LayoutPath.Start)", 0));
- DoubleAnimation startPropertyAnimation = new DoubleAnimation();
- Storyboard.SetTarget(startPropertyAnimation, pathListBox);
- Storyboard.SetTargetProperty(startPropertyAnimation, propertyPath);
- this.rouletteAnimationStoryboard.Stop();
- this.rouletteAnimationStoryboard.Children.Clear();
- this.rouletteAnimationStoryboard.Children.Add(startPropertyAnimation);
- int randomOffset = new Random(Environment.TickCount).Next(1, 100);
- Duration calculatedDuration = this.Duration;
- int nIterations = 1;
- if (this.Duration.TimeSpan.TotalSeconds <= 1)
- {
- calculatedDuration = new Duration(new TimeSpan(0, 0, 1));
- }
- nIterations = ((int)calculatedDuration.TimeSpan.TotalSeconds * this.Speed) / itemsCount;
- if (nIterations < 1)
- nIterations = 1;
- startPropertyAnimation.Duration = calculatedDuration;
- startPropertyAnimation.To = (double)(100 * nIterations + randomOffset) / 100.0;
- var easing = new CircleEase();
- easing.EasingMode = EasingMode.EaseOut;
- startPropertyAnimation.EasingFunction = easing;
- this.rouletteAnimationStoryboard.Begin();
- }
If we try this now the items will spin (the items are not actually spinning we are changing Start property of the layout path and that makes it look like spinning). but we didn’t specify yet how we will select the winning item, so what we need to do is that while the items are virtually spinning we need to change the selected item or more specifically change the SelectedIndex property. The problem is that we need to keep changing the SelectedIndex value as long as the Start property value is changing, how we do this by binding the two properties. so we will add the following code to the OnAttached method
- Binding binding = new Binding();
- PropertyPath propertyPath = new PropertyPath("LayoutPaths[0].Start");
- binding.Path = propertyPath;
- binding.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
- var converter = new StartToIndexConverter(AssociatedObject);
- binding.Converter = converter;
- binding.Mode = BindingMode.TwoWay;
- AssociatedObject.SetBinding(ListBox.SelectedIndexProperty, binding);
The code binds the SelectedIndex property to the Start property of the first LayoutPath (this behavior supports 1 LayoutPath), we need a custom IValueConverter to convert the value of the Start property to a correct SelectedIndex property that’s where the StartToIndexConverter comes into play, the two functions that we need to implement in the IValueConverter interface are shown below
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (this._pathListBox == null)
- return 0;
- int index = 0;
- double capacity = 0;
- if (double.IsNaN(this._pathListBox.LayoutPaths[0].Capacity))
- capacity = this._pathListBox.Items.Count;
- else
- capacity = this._pathListBox.LayoutPaths[0].Capacity;
- double start = (double)value;
- double shift = _previousValue - start;
- double spacing = (this._pathListBox.LayoutPaths[0].Span / capacity);
- Debug.WriteLine("Current Start:{0}", start.ToString());
- if (Math.Abs(shift) > spacing)
- {
- _previousValue = start;
- if (shift > 0)
- if (this._pathListBox.SelectedIndex >= (this._pathListBox.Items.Count - 1))
- index = 0;
- else
- index = this._pathListBox.SelectedIndex + 1;
- else
- if (this._pathListBox.SelectedIndex <= 0)
- index = this._pathListBox.Items.Count - 1;
- else
- index = this._pathListBox.SelectedIndex - 1;
- }
- else
- index = this._pathListBox.SelectedIndex;
- PathListBoxItem itemToBeSelected = (PathListBoxItem)this._pathListBox.ItemContainerGenerator.ContainerFromIndex(index);
- if (itemToBeSelected != null && !itemToBeSelected.IsArranged)
- {
- if (shift > 0)
- index = GetFirstArrangedIndex(0);
- else
- index = GetLastArrangedIndex(0);
- }
- return index;
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- return this._pathListBox.LayoutPaths[0].Start;
- }
Basically what this conversion does is that if the Start value is increased/decreased by an amount that’s greater than the spacing between the items, the converter increments/decrements the SelectedIndex value to move to the next/previous item. we need to make sure that SelectedIndex value remains within the range of the items that are actually visible on the Path that’s why we are checking the PathListBoxItem.IsArranged property.
Once we finish the Behavior, you can drag it from the Assets window and drop it on your PathListBox, then you can change its properties accordingly
PS: This behavior will not work correctly if you are using PathListBoxScrollBehavior.ScrollSelectedCommand
You can download the RegistrationBooth from here.
And you can download a Demo for using the RouletteBehavior from here
Comments