Posts tagged: Dependency Properties

Custom Slider Control – The Base Class

This is part 2 of a multi-part article on a custom Slider control.  You can find the other articles here:

The source code is now available on CodePlex

The purpose of this article is to start digging into some of the details behind the updated Slider control.  The best place to start is with the underlying base class.  The standard slider that comes with Silverlight has a base class called RangeBaseand can be found in the System.Windows.Controls.Primitives namespace.  This class defines the standard properties (Minimum, Maximum, LargeChange, SmallChange and Value).  Minimum and Maximum describe the lower and upper range of the slider itself will Value reflects the current value of the slider (where the thumb currently is located).  LargeChange and SmallChange indicate a value that will be used to increment/decrement the value property.  The RangeBase class also defines the ValueChanged event, which is fired when the Value property changes, and ensures all properties are correctly coerced (which I describe in more detail further down).

One of the main requirements for the new Slider was to be able to select a range of values (an upper and lower bound) rather than just a single value.  Since I still wanted to support everything else offered by RangeBase, I created DualRangeBase which inherits from it.  This became the base class for my version of the Slider control.

This new base class provides three additional properties:  LowerRangeValue, UpperRangeValue and  RangeValueLowerRangeValue and UpperRangeValueprovide the lower and upper values of the range (dictated by the position of the lower and upper thumbs repectively) while the RangeValue is the difference between the lower and upper values.  The DualRangeBase also adds three additional events:  LowerRangeValueChanged, UpperRangeValueChanged and RangeChanged.  The first two can be used if you want to handle the events separately while RangeChanged is fired any time either value changes.

The code snippet below shows the definitions of these properties.

// Defines the LowerRangeValue dependency property.
public static readonly DependencyProperty LowerRangeValueProperty = DependencyProperty.Register("LowerRangeValue", typeof(double), typeof(DualRangeBase), new PropertyMetadata(0.2d, OnLowerRangeValuePropertyChanged));

// Gets or sets the LowerRangeValue of the range.
public double LowerRangeValue
{
     get { return (double)GetValue(LowerRangeValueProperty); }
     set { SetValue(LowerRangeValueProperty, value); }
}

// Defines the UpperRangeValue dependency property.
public static readonly DependencyProperty UpperRangeValueProperty = DependencyProperty.Register("UpperRangeValue", typeof(double), typeof(DualRangeBase), new PropertyMetadata(0.8d, OnUpperRangeValuePropertyChanged));

// Gets or sets the UpperRangeValue of the range.
public double UpperRangeValue
{
     get { return (double)GetValue(UpperRangeValueProperty); }
     set { SetValue(UpperRangeValueProperty, value); }
}

///
/// Gets the size of the current range based on the difference
/// between the lower and upper range values.
///
public double RangeValue
{
    get { return UpperRangeValue - LowerRangeValue; }
}

The trickiest part of the base class, for me, was dealing with coercion.  I got the concept of this from the source code of the RangeBase class which uses coercion as well.  The concept of this is to ensure that when the value of any of the main properties (such as Maximum) is set it undergoes a set of validation checks.  If any of these checks fail the value is changed appropriately.  Coercion occurs during the properties PropertyChanged event handler.  For instance, the UpperRangeValue cannot be greater than the Maximum value.  If it is, the value is changed to equal Maximum.  You can imagine the trouble this can cause.  A single change to a value can cause a recursive loop of multiple changes.

This issue is at its worse when property values are being set during Design Time or the values are programmatically set within the code.  Let’s look at the previous example again and say that you want to set UpperRangeValue to 80.  Since we haven’t yet set Maximum to 100 (our target), the default value of 1 is used when the UpperRangeValue is coerced, which causes it to be set to 1 (the current value of Maximum).  Now you can see the difficulty I had ensuring the coercion between all the properties worked correctly to ensure the intended values got used.  I was able to overcome the issue (mentioned in the example) by coding the coercion process in a way that it remembered the intended value and attempts to use it when it can.  This means, in the example, after the Maximum is set to 100, the intended UpperRangeValue of 80 is applied.

In an attempt to understand this better, lets take a close look at the OnUpperRangeValuePropertyChanged method (which is called when the UpperRangeValue dependency property changes.

DualRangeBase dualRangeBase = d as DualRangeBase;

// Validate the provided UpperRangeValue.
if (!IsValidDoubleValue(e.NewValue))
{
    throw new ArgumentException("Invalid double value", UpperRangeValueProperty.ToString());
}

This beginning portion of the method simply creates an instance (since the method is static) of the DualRangeBase that called it and checks to ensure that the NewValue is valid.

// The code that follows is borrowed from the Microsoft code in RangeBase
// that performs the same actions on the Value property.  The trick here
// is to hold calls to the property changed methods until after all
// coercion has completed.
if (dualRangeBase.levelsFromUpperRootCall == 0)
{
    dualRangeBase.requestedUpperRangeValue = (double)e.NewValue;
    dualRangeBase.preCoersionUpperRangeValue = (double)e.NewValue;
    dualRangeBase.initialUpperRangeValue = (double)e.OldValue;
}
dualRangeBase.levelsFromUpperRootCall++;

This portion of the method saves the new value (requestedUpperRangeValue), the new value before it has been coerced (preCoersionUpperRangeValie) and the old value (initialUpperRangeValue).  These values are used later as part of the coercion testing.  If you remember from what I mentioned earlier, coercion can cause the value to be changed multiple times in an almost recursive manner.  levelsFromUpperRootCall is used to determine the current phase of this process.  I must thank Microsoft for this idea as it is how they did it and it works very well.

// Coerce values
dualRangeBase.CoerceUpperValue();

// This portion of the borrowed Microsoft code finally fires
// the change events once all coercion is confirmed complete.
dualRangeBase.levelsFromUpperRootCall--;
if (dualRangeBase.levelsFromUpperRootCall == 0)
{
    double value = dualRangeBase.UpperRangeValue;
    if (dualRangeBase.initialUpperRangeValue != value)
    {
        dualRangeBase.OnUpperRangeValueChanged(dualRangeBase.initialUpperRangeValue, value);
        dualRangeBase.OnRangeChanged(dualRangeBase.initialLowerRangeValue, dualRangeBase.LowerRangeValue, dualRangeBase.initialUpperRangeValue, value);
    }
}

The above code covers the last part of the method. First, the call to the coersion method is made. I talked about this a little bit already but the biggest thing to remember here is that the value being changed may actually be changed again during coersion. Once coersion has been completed, and the process has returned back to the initial call to the method, the OnUpperRangeValueChanged and OnRangeChanged events are fires.

That pretty much concludes the base class.  I know that might seem a bit confusing but you will understand my points if you step through the code once in Debug-mode.  All of the work that was put into the coercion functions allows the control to behave property when the properties are being set in the XAML in either Blend or the Visual Studio designer.  It also ensures only the appropriate values can be set.  I included a set of unit tests specifically for testing this and suggest you examine those in detail for further understanding.

WordPress Themes