Probably the first most important thing to mention here is that only inheritors of System.Windows.DependencyObject can be extended with dependency properties. This is needed because either to set or to get value for a specific dependency property, you need to use the methods SetValue and GetValue which are defined in the DependencyObject class.
When you declare a dependency property, many advantages are coming out of the box for you such as caching, data binding, default values, expressions, styling, property invalidation and more.
In order to declare a dependency property in Silverlight, you have to follow few simple steps as explained in the sample code below.
C#
public partial class MySilverlightControl : UserControl
{
//1. Declare the dependency property as static, readonly field in your class.
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
"MyProperty", //Property name
typeof( string ), //Property type
typeof( MySilverlightControl ), //Type of the dependency property provider
new PropertyMetadata( MyPropertyChanged ) );//Callback invoked on property value has changes
public MySilverlightControl()
{
InitializeComponent();
}
//2. Create the property and use the SetValue/GetValue methods of the DependencyObject class
public string MyProperty
{
set
{
this.SetValue( MyPropertyProperty, value );
}
get
{
return ( string )this.GetValue( MyPropertyProperty );
}
}
private static void MyPropertyChanged( object sender, DependencyPropertyChangedEventArgs args )
{
//Do some processing here...
}
}
Read more about DependencyObject and DependencyProperty classes on MSDN.
That's it!