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);
}