Reputation: 2454
A WPF dependency property can be given a default value by passing a PropertyMetadata
with the default value to the Register
function:
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
new PropertyMetadata(0.0));
What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata
or by using a PropertyMetadata
constructor which doesn't specify a default value?
This page says
(For cases where a property registration does not specify metadata, a default PropertyMetadata is created with default values for that class.)
but I haven't found anywhere that describes what these default values are.
Upvotes: 2
Views: 2226
Reputation: 11367
The reference code below is what is called by the DependencyProperty
when no default value was given by the PropertyMetadata
.
It uses the standard default values in most cases (null
for reference types, zeroed for value types), but for enums it uses the first enumerator instead of the enumerator with the value 0 (if they are different).
private static object GetDefaultValue(string name, System.Type propertyType, System.Type ownerType)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name");
if (propertyType == null)
throw new ArgumentNullException("propertyType");
if (ownerType == null)
throw new ArgumentNullException("ownerType");
object defaultValue = null;
if (propertyType.IsValueType)
{
try
{
if (propertyType.IsEnum)
{
Array values = Enum.GetValues(propertyType);
if (values.Length > 0)
defaultValue = values.GetValue(0);
else
defaultValue = Activator.CreateInstance(propertyType);
}
else
defaultValue = Activator.CreateInstance(propertyType);
}
catch
{
}
}
return defaultValue;
}
Upvotes: 2
Reputation: 169330
What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?
The default value is the default value of the type of the dependency property, i.e. for a double
dependency property it is 0.0
(or default(double)
).
You can easily confirm this yourself by creating an instance of your class and access the getter of CLR wrapper of the dependency property:
MyControl ctrl = new MyControl();
var x = ctrl.MyProperty; // = 0
Upvotes: 2