// ----------------------------------------------------------------------- // // Copyright 2015 MIT Licence. See licence.md for more information. // // ----------------------------------------------------------------------- namespace Perspex.Controls.Primitives { using System; using Perspex.Utilities; /// /// Base class for controls that display a value within a range. /// public abstract class RangeBase : TemplatedControl { /// /// Defines the property. /// public static readonly PerspexProperty MinimumProperty = PerspexProperty.Register( nameof(Minimum), validate: ValidateMinimum); /// /// Defines the property. /// public static readonly PerspexProperty MaximumProperty = PerspexProperty.Register( nameof(Maximum), defaultValue: 100.0, validate: ValidateMaximum); /// /// Defines the property. /// public static readonly PerspexProperty ValueProperty = PerspexProperty.Register( nameof(Value), validate: ValidateValue); /// /// Initializes a new instance of the class. /// public RangeBase() { AffectsValidation(MinimumProperty, MaximumProperty, ValueProperty); AffectsValidation(MaximumProperty, ValueProperty); } /// /// Gets or sets the minimum value. /// public double Minimum { get { return this.GetValue(MinimumProperty); } set { this.SetValue(MinimumProperty, value); } } /// /// Gets or sets the maximum value. /// public double Maximum { get { return this.GetValue(MaximumProperty); } set { this.SetValue(MaximumProperty, value); } } /// /// Gets or sets the current value. /// public double Value { get { return this.GetValue(ValueProperty); } set { this.SetValue(ValueProperty, value); } } /// /// Throws an exception if the double valus is NaN or Inf. /// /// The value. /// The name of the property being set. private static void ValidateDouble(double value, string property) { if (double.IsInfinity(value) || double.IsNaN(value)) { throw new ArgumentException($"{value} is not a valid value for {property}."); } } /// /// Validates the property. /// /// The RangeBase control. /// The value. /// The coerced value. private static double ValidateMinimum(RangeBase sender, double value) { ValidateDouble(value, "Minimum"); return value; } /// /// Validates/coerces the property. /// /// The RangeBase control. /// The value. /// The coerced value. private static double ValidateMaximum(RangeBase sender, double value) { ValidateDouble(value, "Maximum"); return Math.Max(value, sender.Minimum); } /// /// Validates/coerces the property. /// /// The RangeBase control. /// The value. /// The coerced value. private static double ValidateValue(RangeBase sender, double value) { ValidateDouble(value, "Value"); return MathUtilities.Clamp(value, sender.Minimum, sender.Maximum); } } }