Delay's Blog is the blog of David Anson, a Microsoft developer who works with the Silverlight, WPF, Windows Phone, and web platforms.
Set DependencyProperty default values in a class's default style if it's more convenient
In the previous tip, I explained why it's usually wrong to assign a value to a Silverlight/WPF DependencyProperty in the constructor for a class. The preferred way is to pass the default value in the call to Register, but there's another good option: set the property's starting value in the default Style for the control by putting it in generic.xaml. A control's default style is applied when it is first created and the corresponding changes to its DependencyProperty values have very low precedence (though not as low as the default value passed to Register). Therefore, this is a safe place to set default values without the risk of overriding application-level customizations. A nice benefit of this approach is that it allows the value to be specified in XAML - which offers a designer-friendly syntax and can sometimes be easier to understand. In the example below, a rather complicated Brush is constructed in XAML; the matching code to create that same brush would not be as clear. Next time: Something to watch out for when setting default values.
<GradientStop Color="Red" Offset="0"/>
<GradientStop Color="Green" Offset="0.5"/>
<GradientStop Color="Blue" Offset="1"/>