If you are familiar with WPF, you may be used to setting a dependency property's default value through its property metadata. Unfortunately SL2B2 (Silverlight 2 Beta 2) does not support specifying the default value via the metadata. This was shocking to me as coders often need to check to see if a property has been set or not. So what value is returned if the property is not set? According to this article, it depends on the data type. Reference-type dependency properties will be null, value-types are the default constructed value (double = 0.0), strings will be an empty string.
So I figured I could use the Nullable(Of T) generic structure as the data type of my dependency property to get around this limitation. Doing this would allow me to test to see if the dependency property has been set or not by simply coding something like this: PropertyName.HasValue. This works great programmatically, but I soon found that setting the dependency properties via XAML caused parser exceptions. I also lost my intellisense when coding in XAML. I've posted on the MS Silverlight forums to get an answer why Nullable(Of T) generic structures' XAML are unable to be parsed. "Unfortunately XAML doesn't support Nullable types because they're generic types".
So here's my solution. We found that we cannot use property metadata to set default values and we found that Nullable(Of T) generic data type structures for dependency properties do not play well with XAML. Instead I just set my dependency property values when the object is constructed.
Partial Public Class SilverlightControl1
Inherits UserControl
Public Shared ReadOnly ColorProperty As DependencyProperty = DependencyProperty.Register("Color", GetType(Color), GetType(SilverlightControl1), Nothing)
Public Property Color() As Color
Get
Return CType(GetValue(SilverlightControl1.ColorProperty), Color)
End Get
Set(ByVal value As Color)
SetValue(SilverlightControl1.ColorProperty, value)
End Set
End Property
Public Sub New()
InitializeComponent()
'set dependency property default value
Me.Color = Colors.Transparent
End Sub
End Class
** Edit 9/30/2008 **
SL2RC0 (Silverlight 2 Release Candidate 2) now allows programmers to set a custom depencency property's default value! Simply construct a new PropertyMetadata object and pass in the default value.