Search code examples
wpfxamlattached-propertiesdesign-decisions

Why does WPF use attached properties for things like positioning in a grid?


Why do we need "attached properties"? The concept of it bugs me a bit, since you can conceivably set values of properties that don't even exist on a particular DependencyObject (and they will just be silently ignored). It almost seems like a solution looking for a problem--why not just do what e.g. HTML does and have the parent element determine things like positioning for children explicitly?

That is, instead of:

<Grid>
  <Grid.ColumnDefinitions>
    <!-- etc. -->
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <!-- etc. -->
  </Grid.RowDefinitions>
  <SomeElement Grid.Column="0" Grid.Row="0" />
  <!-- etc. -->
</Grid>

Why not something like this (the equivalent of <tr> and <td> in HTML):

<Grid>
  <Grid.Row>
    <Grid.Column>
      <SomeElement />
    </Grid.Column>
    <!-- etc. -->
  </Grid.Row>
</Grid>

Perhaps grids are just a bad example, and attached properties make more sense in other contexts? Or maybe I'm missing something altogether?


Solution

  • The most obvious reason that you need attached properties to position elements in a grid is so that you can use binding:

    <Grid.ItemContainerStyle>
       <Style TargetType="ContentPresenter">
          <Setter Property="Grid.Row" Value="{Binding Row}"/>
          <Setter Property="Grid.Column" Value="{Binding Column}"/>
       </Style>
    </Grid.ItemContainerStyle>
    

    To implement comparable functionality in HTML you have to write code that explicitly removes and re-adds an element when its row and/or column number changes.