This is the online documentation for PostSharp 5.0.
Download PDF or CHM. Go to v4.3 or v5.0

Dependency Property

Dependency properties are based on the WPF property system and extend the functionality of the CLR properties with features such as data binding, styling, animation, etc. Whenever you need to define a property with some of these advanced features in your XAML application, you typically have to follow a strict implementation pattern and write some amount of boilerplate code. This article shows how you can create custom dependency properties with PostSharp faster and without writing repetitive code.

This topic contains the following sections:

Creating a simple dependency property

To add a new dependency property to your class

  1. Add a new property to your class with a chosen name, type and a public getter and setter.

  2. Mark your new property with the DependencyPropertyAttribute attribute.

Declaring a new dependency property
[DependencyProperty]
public string Phone { get; set; }
Using the dependency property

After you have marked your property with the DependencyPropertyAttribute attribute, you can use it with any of the WPF property system features. For example, you can set the value of the property using the data binding mechanism in XAML.

XAML
<local:ContactCard FullName="{Binding ContactName}" Phone="{Binding ContactPhone}" Email="{Binding ContactEmail}" Notes="{Binding ContactNotes}"
                   x:Name="CurrentContactCard" HorizontalAlignment="Left" Margin="478,270,0,0" VerticalAlignment="Top" Background="Bisque"/>

If you want to manipulate the dependency property using the WPF property system API, then you need to acquire a corresponding instance of the DependencyProperty class. To get a DependencyProperty instance that is backing your dependency property, call the static GetDependencyProperty(Type, String) method of the DependencyPropertyServices class. See the DependencyPropertyServices class documentation for more method overloads.

C#
DependencyProperty phoneProperty = DependencyPropertyServices.GetDependencyProperty(typeof(ContactCard), "Phone");
this.CurrentContactCard.SetBinding(phoneProperty, "ContactPhone");
Validating the value of the dependency property

PostSharp Code Contracts (see Contracts) provide a convenient way to validate the values of the dependency properties. To add the validation to your dependency property, you just need to apply a Code Contracts attribute to that property.

Validating the dependency property using code contract
[DependencyProperty]
[NotEmpty]
public string FullName { get; set; }

If you need more complex validation for your dependency property, you can implement it in a dedicated validation method. To define a validation method for the Email dependency property, add a new method named ValidateEmail to the same class where the property is declared. The method must accept one argument with the type assignable from the property type and return a bool value. Implement the validation logic inside this new method. Return true if the argument represents a valid property value, or false otherwise.

Validating the dependency property using validation method
[DependencyProperty]
public string Email { get; set; }

private bool ValidateEmail(string value)
{
    return EmailRegex.IsMatch(value);
}

The following list shows the method signatures you can use when implementing the validation method. TValue can be a generic parameter or any type assignable from the property type. TDeclaringType is the class where your property is declared.

  • static bool ValidatePropertyName(TValue value)

  • static bool ValidatePropertyName(DependencyProperty property, TValue value)

  • static bool ValidatePropertyName(TDeclaringType instance, TValue value)

  • static bool ValidatePropertyName(DependencyProperty property, TDeclaringType instance, TValue value)

  • bool ValidatePropertyName(TValue value)

  • bool ValidatePropertyName(DependencyProperty property, TValue value)

Reacting to the changes of the dependency property value

The WPF property system can automatically notify you about the dependency property value changes via callback methods. This can be useful when, for example, you need to update the visual presentation of your custom UI control in response to a change of its property. This section shows how you can define a property change callback method with the PostSharp's dependency property pattern.

To define a property change callback method for the PictureUrl dependency property, add a new method named OnPictureUrlChanged to the same class where the property is declared. The method doesn't have to accept any arguments and must have a void return type. Implement your property change handling logic inside this new method.

Reacting to the change of the dependency property value using callback method
[DependencyProperty]
public string PictureUrl { get; set; }

private void OnPictureUrlChanged()
{
    this.ProfileImage.Source = this.LoadImageFromUrl(this.PictureUrl);
}

The following list shows the method signatures you can use when implementing the property change callback method. TDeclaringType is the class where your property is declared.

  • static bool OnPropertyNameChanged()

  • static bool OnPropertyNameChanged(DependencyProperty property)

  • static bool OnPropertyNameChanged(TDeclaringType instance)

  • static bool OnPropertyNameChanged(DependencyProperty property, TDeclaringType instance)

  • bool OnPropertyNameChanged()

  • bool OnPropertyNameChanged(DependencyProperty property)

You may also want to notify the users of your class when a dependency property value changes. In this case you would normally need to implement the INotifyPropertyChanged interface in your class and raise the PropertyChanged event. PostSharp helps you to automate this task using INotifyPropertyChanged pattern. To raise the PropertyChanged event every time any of the dependency properties in your class changes its value, mark your class with the NotifyPropertyChangedAttribute attribute.

C#
[NotifyPropertyChanged]
public partial class ContactCard : UserControl
{
    // ...
Customizing the names of the dependency property's methods and properties

PostSharp follows a predefined naming convention when looking for methods and properties associated with the dependency property in your class. You can override the naming convention and choose your own member names by setting properties on the DependencyPropertyAttribute. The following table shows the default naming convention and the properties used to override member names.

Dependency property pattern's naming conventions

Member kind

Default name

Example

Set this property to override

Value validation method

ValidatePropertyName

ValidateCurrentValue

ValidateValueMethod

Property changed callback method

OnPropertyNameChanged

OnCurrentValueChanged

PropertyChangedMethod

Registration property

PropertyNameProperty

CurrentValueProperty

RegistrationProperty

C#
[DependencyProperty(ValidateValueMethod = "ValidateStringMaxLength" )]
public string Notes { get; set; }

private bool ValidateStringMaxLength(string value)
{
    if (string.IsNullOrEmpty(value))
        return true;

    return value.Length <= MAX_LENGTH;
}
See Also