Export (0) Print
Expand All

DependencyPropertyKey.OverrideMetadata Method

Overrides the metadata of a read-only dependency property that is represented by this dependency property identifier.

Namespace:  System.Windows
Assembly:  WindowsBase (in WindowsBase.dll)

public void OverrideMetadata(
	Type forType,
	PropertyMetadata typeMetadata
)

Parameters

forType
Type: System.Type

The type on which this dependency property exists and metadata should be overridden.

typeMetadata
Type: System.Windows.PropertyMetadata

Metadata supplied for this type.

ExceptionCondition
InvalidOperationException

Attempted metadata override on a read-write dependency property (cannot be done using this signature).

ArgumentException

Metadata was already established for the property as it exists on the provided type.

Overriding metadata on a read-only dependency property is done for similar reasons as overriding metadata on a read-write dependency property, and is restricted to access at the key level because behaviors specified in the metadata can change the set behavior (the default value, for instance).

As with read-write dependency properties, overriding metadata on a read-only dependency property should only be done prior to that property being placed in use by the property system (this equates to the time that specific instances of objects that register the property are instantiated). Calls to OverrideMetadata should only be performed within the static constructors of the type that provides itself as the forType parameter of this method, or equivalent initialization for that class.

This method effectively forwards to the OverrideMetadata method, passing the DependencyPropertyKey instance as the key parameter.

The following example overrides metadata for an existing read-only dependency property that a class inherits. In this case, the scenario goal was to add a coerce value callback that the base property metadata did not have. You could also override metadata for any of the other reasons that overriding metadata is typically appropriate (changing default value, adding FrameworkPropertyMetadataOptions values, etc.)

static Fishbowl() {
  Aquarium.AquariumSizeKey.OverrideMetadata(
    typeof(Aquarium),
    new PropertyMetadata(
      double.NaN,
      null,
      new CoerceValueCallback(CoerceFishbowlAquariumSize)
    )
  );
}

static object CoerceFishbowlAquariumSize(DependencyObject d,Object baseValue)
{
    //Aquarium is 2D, a Fishbowl is a round Aquarium, so the Size we return is the ellipse of that height/width rather than the rectangle
    Fishbowl fb = (Fishbowl)d;
    //other constraints assure that H,W are positive 
    return Convert.ToInt32(Math.PI * (fb.Width / 2) * (fb.Height / 2));
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Show:
© 2015 Microsoft