soumyasg
soumyasg

Reputation: 33

Grid's attached properties always available?

In the xaml for this window I deleted the Grid container and put a DockPanel. Yet, I can access a Grid's attached properties from the DockPanel. How is this possible?

Thanks!

<Window x:Class="testWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="testWindow" Height="300" Width="300">
    <DockPanel Grid.Column="2">

    </DockPanel>
</Window>

Upvotes: 0

Views: 90

Answers (1)

Troels Larsen
Troels Larsen

Reputation: 4651

Because the properties are not on the instance, but are attached - meaning they are defined statically on the Grid class, and that the values are stored in a property container outside of the normal property system.

If you have a DockPanel within a Grid, you use Grid.Column to set which column the DockPanel should be on. Hence, they can be very useful. Attached dependency properties can also be inherited from the parent tree.

For more information, read this link:

http://www.abhisheksur.com/2011/07/internals-of-dependency-property-in-wpf.html

If we take the Grid.Column example, the internals are that somewhere in the Grid class lies a definition like this:

public static readonly DependencyProperty ColumnProperty =
    DependencyProperty.RegisterAttached(
        "Column",
        typeof(int),
        typeof(Grid),
        new PropertyMetadata(0));

The above code is in fact all that is needed to declare an attached dependency property. Note that there is no getter nor setter here and that the property is static. All it is, is a declaration of behavior - there is no logic to store or retrieve it.

This is because WPF has its own internal store for Dependency Properties (DPs). A normal DP has no backing fields on the classes either. In other words, all DPs are stored internally by WPF. However, WPF still keeps track of which values belong to which instances, so it is still possible to store a Width = 20 for TextBox1. It also means that it is possible to store values that aren't even defined on the classes themselves - as is the case with attached DPs.

Since there are no rules for which controls Grid.Column can be set on, it can be stored even on controls that are not children of a Grid control.

Upvotes: 1

Related Questions