Wednesday, March 26, 2014

#166 – You Can Override Metadata for Any Dependency Property

Inline image 1

    Recall that you can set a dependency property value on a DependencyObject for any dependency property, not just the properties that the class implements or inherits.
Since any dependency property can be attached to any dependency object, you can override metadata for any dependency property in a class.

Here's an example where we override the Grid.Row and Grid.Column properties in a class that derives from Button.  If this ButtonLoner object is defined in a Grid in XAML, it will automatically appear in Row 1, Col 1, rather than Row 0, Col 0.

public class ButtonLoner : Button
{
    static ButtonLoner()
    {
        Grid.RowProperty.OverrideMetadata(typeof(ButtonLoner), new FrameworkPropertyMetadata(1));
        Grid.ColumnProperty.OverrideMetadata(typeof(ButtonLoner), new FrameworkPropertyMetadata(1));
    }
}

Here is example:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <app:ButtonLoner x:Name="btnLoner" Content="Loner" Width="100" Height="25"/>
</Grid>