Dependency Properties

Probably not the most thrilling first post, but Dependency Properties are a big thing in WPF land.

A Dependency Property is a property that is registered with the Avalon Dependency property system. This is useful for 2 main reasons...

  • Backing your object property with a dependency property, allowing you to have support for databinding, styling, animation, default values, value expressions, property invalidations or inheritance. Examples include the Background or Fontsize property.
  • Creating attached properties. Attached properties are properties that can be set on ANY DependencyObject types. An example is the Dock property.

You can get the full low down on Dependency Properties here.

So, for reference, the code below shows how to create and register a Dependency Property within a class. The property is call 'MyNameProperty'. The code below declares and registers the Dependency property...

public

static readonly DependencyProperty MyNameProperty = DependencyProperty.Register("MyName", typeof(string), typeof(MyClass), new UIPropertyMetadata(MyClass.MyNameValueChanged));

This next piece of code now provides access to the property...

public

string MyName{

   get { return (string)GetValue(MyNameProperty); }

   set { SetValue(MyNameProperty, value); }

}

Finally, I add an event to listen for the value changing - for example, if the property is animated or databound... (where 'nameText' is a TextBlock displaying the value of MyName)

private

static void MyNameValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){

MyClass myClass = (MyClass)d;

myClass.nameText.Text = (

string)e.NewValue;

}

I can now use MyClass as a DataTemplate within an items control, binding MyName to a data context...

<

ItemsControl Name="nameList" ItemsSource="{Binding}">

<

ItemsControl.ItemTemplate>

<

DataTemplate>

<

local:MyClass MyName="{Binding Path=MyName}" />

</

DataTemplate>

</

ItemsControl.ItemTemplate>

</

ItemsControl>

And that is a brief intro to dependency properties. I am sure i will go deeper into these in the future as i encounter more and more uses for them.

Martin