RegisterAttached and Register call on DependencyProperty

You sometimes may need to declare a Behavior class and through the behaviour class you can give new behaviour to the element that it's attached to. and therefore the whole tree it belongs to.


Normally the behaviour class is a static class, and the static should have some dependency property registered.



The DependencyProperty.Register call will register a DP, suppose we are registering a DependencyProperty with name "IsLabeled" to change the behaviour on a piechart label to have label on or off.


    public static readonly DependencyProperty IsLabeledProperty =
      DependencyProperty.Register("IsLabeled", typeof(bool), typeof(PieLabelBehavior), new PropertyMetadata(IsLabeledPropertyChanged));



But when you run the app, you probably will have the following error on the application's startup.


       InnerException: System.ArgumentException
            Message='PieLabelBehavior' type must derive from DependencyObject.
            Source=WindowsBase
            StackTrace:
                 at System.Windows.DependencyProperty.SetupOverrideMetadata(Type forType, PropertyMetadata typeMetadata, DependencyObjectType& dType, PropertyMetadata& baseMetadata)
                 at System.Windows.DependencyProperty.OverrideMetadata(Type forType, PropertyMetadata typeMetadata)
                 at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback)
                 at System.Windows.DependencyProperty.Register(String name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
                 at LabeledPieChartLib.PieLabelBehavior..cctor() in C:\MSDE\boqwang\blogs\Bea\src\assemblies\piechart\LabeledPieChart\PieLabelBehavior.cs:line 46
            InnerException: 


So, that is fairly obvious that you can not register a DependencyProperty on a class that is not derived from the class DependencyObject, and a static class is of couse non-inheritable from the DependencyObject.



So you will need to write as follow.


    public static readonly DependencyProperty IsLabeledProperty =
             DependencyProperty.RegisterAttached("IsLabeled", typeof(bool), typeof(PieLabelBehavior), new PropertyMetadata(IsLabeledPropertyChanged));

And you should provide the accessor as follow.


    public static bool GetIsLabeled(DependencyObject obj)
    {
      return (bool)obj.GetValue(IsLabeledProperty);
    }


    public static void SetIsLabeled(DependencyObject obj, bool value)
    {
      obj.SetValue(IsLabeledProperty, value);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值