XAML dependency properties extend the functionality of the CLR properties with features such as data binding, styling, and animation. Whenever you need to define a dependency property in your XAML application, you typically have to follow a strict implementation pattern and write a fair amount of boilerplate code. The DependencyPropertyAttribute aspect allows you to create custom dependency properties much faster, without writing repetitive code.
Creating a simple dependency property
Adding a dependency property to your class
Add a new property to your class with a chosen name, a type, and a public getter and setter.
Mark your new property with the DependencyPropertyAttribute attribute.
After you have marked your property with the DependencyPropertyAttribute attribute, you can immediately start using advanced features in your XAML code.
Example
The following code snippet comes from a custom control named ContactCard. The snippet defines a dependency property named Phone. The custom control defines other dependency properties not listed here.
[DependencyProperty]
public string? Phone { get; set; }
The dependency properties can be used in XAML for advanced features. In the following code snippet, we use data binding with the dependency properties of the ContactCard custom control.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DependencyPropertyExample;assembly=DependencyPropertyExample"
Title="Contact" Height="300" Width="400">
<StackPanel>
<local:ContactCard x:Name="CurrentContactCard"
FullName="{Binding ContactName}" Phone="{Binding ContactPhone}"
Email="{Binding ContactEmail}" Notes="{Binding ContactNotes}" />
<TextBox x:Name="NameTextBox" Text="{Binding ContactName}" />
<TextBox x:Name="EmailTextBox" Text="{Binding ContactEmail}" />
<TextBox x:Name="NotesTextBox" Text="{Binding ContactNotes}" />
</StackPanel>
</Window>
Exposing the DependencyProperty object
If you want to manipulate the dependency property using the XAML API in C# or VB, you need to get the DependencyProperty for this specific property. One solution is to use the GetDependencyProperty(Type, string) method, but this is long and error-prone.
A better solution is to add a public static property of type DependencyProperty with the same name as your dependency property plus the Property suffix. This property is picked up by the DependencyPropertyAttribute aspect and set to the proper DependencyProperty value.
Example
The following example shows how to expose the DependencyProperty for the Phone property.
[DependencyProperty]
public string? Phone { get; set; }
public static DependencyProperty PhoneProperty { get; private set; }
You can then use the PhoneProperty property, for instance to create a binding in C#:
card.SetBinding( ContactCard.PhoneProperty, new Binding( "ContactPhone" ) );
Validating the value of the dependency property with contracts
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 need to apply a contract attribute to that property.
Example
The following code snippet shows how to validate a dependency property using a code contract.
[DependencyProperty]
[NotEmpty]
public string? FullName { get; set; }
Validating the value of the dependency property with a validation method
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 of a type that is assignable from the property type and return a bool value.
The following list shows the method signatures you can use when implementing the validation method, where TPropertyType is the type of the dependency property and TDeclaringType is the class where your property is declared.
static bool ValidatePropertyName(TPropertyType value)static bool ValidatePropertyName(DependencyProperty property, TPropertyType value)static bool ValidatePropertyName(TDeclaringType instance, TPropertyType value)static bool ValidatePropertyName(DependencyProperty property, TDeclaringType instance, TPropertyType value)bool ValidatePropertyName(TPropertyType value)bool ValidatePropertyName(DependencyProperty property, TPropertyType value)
Example
The following code snippet shows how to validate a dependency property using a validation method.
[DependencyProperty]
public string? Email { get; set; }
private bool ValidateEmail( string? value )
{
return value == null || EmailRegex.IsMatch( 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 dependency property pattern of PostSharp.
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 does not have to accept any arguments and must have a void return type. Implement your property change handling logic inside this new method.
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 void OnPropertyNameChanged()static void OnPropertyNameChanged(DependencyProperty property)static void OnPropertyNameChanged(TDeclaringType instance)static void OnPropertyNameChanged(DependencyProperty property, TDeclaringType instance)void OnPropertyNameChanged()void OnPropertyNameChanged(DependencyProperty property)
Example
[DependencyProperty]
public string? PictureUrl { get; set; }
private void OnPictureUrlChanged()
{
this.ProfileImage.Source = this.LoadImageFromUrl( this.PictureUrl );
}
Implementing INotifyPropertyChanged
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 the 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.
[NotifyPropertyChanged]
public class ContactCard : UserControl
{
private const int MAX_LENGTH = 250;
private static Regex EmailRegex = new Regex( @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", RegexOptions.IgnoreCase );
private readonly Image ProfileImage = new Image();
public ContactCard()
{
this.Content = this.ProfileImage;
}
[DependencyProperty]
public string? PictureUrl { get; set; }
private void OnPictureUrlChanged()
{
this.ProfileImage.Source = this.LoadImageFromUrl( this.PictureUrl );
}
private BitmapImage? LoadImageFromUrl( string? url )
{
Console.WriteLine( $"Loading the picture from '{url}'." );
return null;
}
[DependencyProperty]
[NotEmpty]
public string? FullName { get; set; }
[DependencyProperty]
public string? Email { get; set; }
private bool ValidateEmail( string? value )
{
return value == null || EmailRegex.IsMatch( value );
}
[DependencyProperty]
public string? Phone { get; set; }
public static DependencyProperty PhoneProperty { get; private set; }
[DependencyProperty( ValidateValueMethod = nameof(ValidateStringMaxLength) )]
public string? Notes { get; set; }
private bool ValidateStringMaxLength( string? value )
{
if ( string.IsNullOrEmpty( value ) )
{
return true;
}
return value.Length <= MAX_LENGTH;
}
}
The sample program binds the properties of the control, then changes them. It prints the following output:
Bound in XAML: Joe Johnson, joe@example.com, Preferred customer.
Bound in C#: 555-0100
Property changed: FullName
Property changed: PictureUrl
Loading the picture from '/jane.jpg'.
ArgumentNullException: The property 'FullName' cannot be null or empty. (Parameter 'value')
ArgumentException: Invalid property value. (Parameter 'value')
ArgumentException: Invalid property value. (Parameter 'value')
Overriding the naming conventions
The DependencyPropertyAttribute aspect 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 | Override property |
|---|---|---|---|
| Value validation method | Validate PropertyName | ValidatePhoneNumber |
<xref:PostSharp.Patterns.Xaml.DependencyPropertyBaseAttribute.ValidateValueMethod> |
| Property changed callback method | On PropertyName Changed | OnPhoneNumberChanged |
<xref:PostSharp.Patterns.Xaml.DependencyPropertyBaseAttribute.PropertyChangedMethod> |
| Registration property | PropertyName Property | PhoneNumberProperty |
<xref:PostSharp.Patterns.Xaml.DependencyPropertyBaseAttribute.RegistrationProperty> |
Example
[DependencyProperty( ValidateValueMethod = nameof(ValidateStringMaxLength) )]
public string? Notes { get; set; }
private bool ValidateStringMaxLength( string? value )
{
if ( string.IsNullOrEmpty( value ) )
{
return true;
}
return value.Length <= MAX_LENGTH;
}
See Also
Reference
DependencyPropertyAttribute
DependencyProperty
DependencyPropertyServices
NotifyPropertyChangedAttribute
INotifyPropertyChanged
NotEmptyAttribute
Other Resources
Dependency Properties Overview
Contracts
INotifyPropertyChanged