WPFwiki, wpf, wiki, .net 3.0, windows presentation foundation, FAQ, free resources, solution, development, microsoft Home of the world's largest WPF FAQ
Edit

Category

Fundamentals

Edit

Question

What is an Attached DependencyProperty, and what is the difference with a regular DependencyProperty?

Edit

Answer

An Attached DependencyProperty (also called attached property for simplicity) is a DependencyProperty which can be set and read to/from any instance of any DependencyObject (not limited to the declared owner types, as with a regular DependencyProperty).

With this approach, some classes can interact with objects that know nothing about these classes.

A perfect example of attached properties is the Grid class.

The Grid class defines two attached properties: Grid.Row and Grid.Column.

These two attached properties can be used to alter the layout of controls nested under the Grid control without having them know a thing about the Grid class or how the layout is performed in the Grid class.

Example:

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition>
      <ColumnDefinition>
   </Grid.ColumnDefinitions>
   <Grid.RowDefinitions>
      <RowDefinition>
      <RowDefinition>
   </Grid.RowDefinitions>
 
   <Button Grid.Column="0" Grid.Row="1" />
   <Button Grid.Column="1" Grid.Row="0" />

</Grid>


Note: Be aware that attached properties do not require an actual instance of the class that defines them in order to be used. For example, with KeyboardNavigation, you define no instance, but can use its attached properties.

C# Version:

         Grid grid1 = new Grid();

ColumnDefinition coldef1 = new ColumnDefinition(); coldef1.Width = GridLength.Auto; grid1.ColumnDefinitions.Add(coldef1);

ColumnDefinition coldef2 = new ColumnDefinition(); coldef2.Width = GridLength.Auto; grid1.ColumnDefinitions.Add(coldef2);

RowDefinition rowdef1 = new RowDefinition(); rowdef1.Height = GridLength.Auto; grid1.RowDefinitions.Add(rowdef1);

RowDefinition rowdef2 = new RowDefinition(); rowdef2.Height = GridLength.Auto; grid1.RowDefinitions.Add(rowdef2);

Button btn1 = new Button(); grid1.Children.Add(btn1); Grid.SetColumn(btn1, 0); Grid.SetRow(btn1, 1);

Button btn2 = new Button(); grid1.Children.Add(btn2); Grid.SetColumn(btn2, 1); Grid.SetRow(btn2, 0);


pacquiao vs marquez streaming | pacquiao vs marquez | pacquiao vs marquez 3 | Reverse Cell Phone Lookup | Pellet Stoves | Outdoor Lighting | Outdoor Flood Lights | Used Pellet Stoves | Outdoor Security Lights

All content is Copyright ©2007 Xceed Software Inc. unless otherwise indicated. See the Terms of Service. Contributors must read and agree to the Contribution Policy. WPFwiki is brought to you by Xceed, makers of the powerful yet free Xceed DataGrid for WPF.