public static readonly DependencyProperty Color1Property = DependencyProperty.Register("Color1", typeof(Color), typeof(CustomButtonButton), new PropertyMetadata(Colors.Black, OnColorChanged)); public static readonly DependencyProperty Color2Property = DependencyProperty.Register("Color2", typeof(Color), typeof(CustomButton), new PropertyMetadata(Colors.White, OnColorChanged)); public Color Color1 { set { SetValue(Color1Property, value); } get { return (Color)GetValue(Color1Property); } } public Color Color2 { set { SetValue(Color2Property, value); } get { return (Color)GetValue(Color2Property); } }
static void OnColorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { CustomButton btn = obj as CustomButton; if (args.Property == Color1Property) btn.gradientStop1.Color = (Color)args.NewValue; if (args.Property == Color2Property) btn.gradientStop2.Color = (Color)args.NewValue; }
DependencyPropertyChangedEventArgs 的参数里存在着Property属性指向改变的DependencyProperty,并存在着NewValue属性指向改变后的新值,OldValue属性指向改变前的旧值
同时,存在一种简版的方法:
static void OnColorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { CustomButton btn = obj as CustomButton; btn.gradientStop1.Color = btn.Color1; btn.gradientStop2.Color = btn.Color2; }
申明为DependencyProperty的属性,可以进行Style设定:
<phone:PhoneApplicationPage.Resources> <Style x:Key="customButtonStyle" TargetType="local:CustomButton"> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="Color1" Value="Cyan" /> <Setter Property="Color2" Value="Pink" /> </Style> </phone:PhoneApplicationPage.Resources>
------------------------------------------------------------------------------------------
RoutedPropertyChangedEventHandler可以提供一个共外部使用的事件处理:
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(byte), typeof(ColorColumn), new PropertyMetadata((byte)0, OnValueChanged)); … public event RoutedPropertyChangedEventHandler<byte> ValueChanged; … public byte Value { set { SetValue(ValueProperty, value); } get { return (byte)GetValue(ValueProperty); } } … static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { (obj as ColorColumn).OnValueChanged((byte)args.OldValue, (byte)args.NewValue); } protected virtual void OnValueChanged(byte oldValue, byte newValue) { slider.Value = newValue; colorValue.Text = newValue.ToString("X2"); if (ValueChanged != null) ValueChanged(this, new RoutedPropertyChangedEventArgs<byte>(oldValue, newValue)); } …