标签:
自定义一个Range类型,利用CoerceValueCallback和PropertyChangeCallback实现三个属性Min,Max,Value,使其效果类似于Slider。Min总小于Max,并且Value总介于Min和Max之间。
public class Range : DependencyObject { public int Min { get { return (int)GetValue(MinProperty); } set { SetValue(MinProperty, value); } } public int Max { get { return (int)GetValue(MaxProperty); } set { SetValue(MaxProperty, value); } } public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty MinProperty; public static readonly DependencyProperty MaxProperty; public static readonly DependencyProperty ValueProperty; public static FrameworkPropertyMetadata minMetadata; public static FrameworkPropertyMetadata maxMetadata; public static FrameworkPropertyMetadata valueMetadata; static Range() { minMetadata = new FrameworkPropertyMetadata(); maxMetadata = new FrameworkPropertyMetadata(1); // Max的默认值为1 valueMetadata = new FrameworkPropertyMetadata(); minMetadata.CoerceValueCallback = MinCoerce; maxMetadata.CoerceValueCallback = MaxCoerce; valueMetadata.CoerceValueCallback = ValueCoerce; minMetadata.PropertyChangedCallback = MinChanged; maxMetadata.PropertyChangedCallback = MaxChanged; MinProperty = DependencyProperty.Register("Min", typeof(int), typeof(Range), minMetadata); MaxProperty = DependencyProperty.Register("Max", typeof(int), typeof(Range), maxMetadata); ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(Range), valueMetadata); } public static object MinCoerce(DependencyObject d, object baseValue) { Range range = (Range)d; if ((int)baseValue > range.Max) return range.Max; else return (int)baseValue; } public static object MaxCoerce(DependencyObject d, object baseValue) { Range range = (Range)d; if ((int)baseValue < range.Min) return range.Min; else return (int)baseValue; } public static object ValueCoerce(DependencyObject d, object baseValue) { Range range = (Range)d; int value = (int)baseValue; if (value < range.Min) return range.Min; else if (value > range.Max) return range.Max; else return value; } public static void MinChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Range range = (Range)d; range.CoerceValue(Range.MaxProperty); // Coerces the value of Dependcy Property range.CoerceValue(Range.ValueProperty); } public static void MaxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Range range = (Range)d; range.CoerceValue(Range.MinProperty); range.CoerceValue(Range.ValueProperty); } }
// 执行以下语句,观察值的变化 Range range = new Range(); //Min=0, Max=1, Value=0 range.Value = 100; //Min=0, Max=1, Value=1 range.Min = 1; //Min=1, Max=1, Value=1 range.Max = 200; //Min=1, Max=200, Value=100
执行到最后一句时,当Max属性被改变之后,它会触发对Min和Value的强制。这一强制动作作用于最初设定的值。换句话说,WPF以依赖属性系统仍然保存了本地值100,并且现在该数值是可以接受的,它可以被应用到Value属性。
CoerceValueCallback 和 PropertyChangeCallBack
标签:
原文地址:http://www.cnblogs.com/liuzeyuzh/p/4263931.html