WPF 强制回调的应用
通过 FrameWorkPropertyMetadata 对象 使用 CoerceValueCallBack回调,下面是一个示例,
FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata();
metadata.CoerceValueCallback = new CoerceValueCallback(CoerceMaxValue); DependencyProperty.Register("Maximum", typeof(double), typeof(RangeBase), metadata);
通过 CoerceValueCallback 回调函数可以处理相互关联的属性,例如Scrolllbal 提供了 Maximum,Minimum
和value的属性。这些属性都继承生RangeBase类。
当设置Maximum属性时,必须进行强制,以确保不能小于Minimun属性的值,
private object CoerceMaxValue(DependencyObject d, object baseValue) { RangeBase base1 = (RangeBase)d; if (((double)baseValue) < base1.Minimum) { return base1.Minimum; } return baseValue; }
1 //设置Vlaue的属性的时候 会发生强制的过程。对Value的属性进行强制,确保不会超过由Minimum属性和 2 //和Maximum属性定义范围 3 internal static object ConstraionToRange(DependencyObject d, object value) 4 { 5 double newvalue = (double)value; 6 RangeBase base1 = (RangeBase)d; 7 double minimum = base1.Minimum; 8 if (newvalue < minimum) 9 { 10 return minimum; 11 } 12 13 double maximum = base1.Maximum; 14 if (newvalue > maximum) 15 { 16 return maximum; 17 } 18 19 return newvalue; 20 } 21 22 //Minimumum 属性根本不会使用值强制,反而,一但值发生了变化,就会发生PropertyChangeCallback,然后通过 23 //手动触发Maximum属性和Value属性的强制过程 24 25 private static void onMinimumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 26 { 27 RangeBase base1 = (RangeBase)d; 28 base1.CoerceValue(RangeBase.MaximumProperty); 29 base1.CoerceValue(RangeBase.ValueProperty); 30 }