Delay's Blog is the blog of David Anson, a Microsoft developer who works with C#, XAML, HTML, and Azure.
This blog has moved to a new location and comments have been disabled.
All old posts, new posts, and future comments can be found on The blog of dlaa.me.
See you there!
Do not assign DependencyProperty values in a constructor; it prevents users from overriding them
Initializing variables in an object's constructor is considered a Good Thing. Traditionally, initialization is done with a simple assignment that sets the variable to its initial value: MyProperty = 10;. However, doing that with a Silverlight/WPF DependencyProperty uses the CLR wrapper (more background here and here) and results in a call to SetValue that sets the local value of that property. The precedence order for DependencyProperty values is such that the local value overrides almost any other value the application may have provided with a Style (normal or implicit) Setter or Trigger. But if a property can't be styled, then much of the goodness of being a DependencyProperty goes out the window... Fortunately, there are two good alternatives; the most direct is to pass the default value in the call to Register. Setting the default value that way is nice because it's easy, it's obvious, and it "just works". And since DependencyProperty default values have the lowest precedence of anything, you don't need to worry about overriding any customizations users may have made. Next time: The other option.
MyProperty = 10;
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
"MyProperty", typeof(int), typeof(MyControl), new PropertyMetadata(123, OnMyPropertyChanged));