Introduction
In order to understand the attached property, first, we must know what dependency property is. This is because attached properties are nothing but a special type of dependency property.
Visit my article on dependency properties.
Again, the answer is in the name itself. It's called an attached property cause they're attached with WPF elements and set by a DependencyObject.SetValue method.
For example, here Grid.row is an attached property of a control Grid and it is applied on a Grid's children, which are Stackpanel, Button & Textblock in this example.
The attached properties are seperated by a dot(.)
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- </Grid.RowDefinitions>
- <StackPanel Orientation="Horizontal" Grid.Row="0">
- <Label x:Name="LabelUserName"
- Content="UserName:"
- VerticalAlignment="Center"
- Margin="200 0 0 0"
- />
- <TextBox x:Name="TextBoxName"
- Text="{Binding UserName}"
- Height="30"
- Width="300"/>
- </StackPanel>
- <Button x:Name="ButtonSubmit"
- Margin="{StaticResource MarginTOP}"
- Content="Submit"
- Height="20"
- Width="100"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"
- Grid.Row="1"/>
- <TextBlock x:Name="TextBlockUserName"
- Text="{Binding UserName}"
- Style="{DynamicResource TextBlockBottomStyle}"
- HorizontalAlignment="Center"
- VerticalAlignment="Top"
- Grid.Row="2"/>
- </Grid>
Grid's control class: as you can see RowProperty of Grid class is an Dependency property, but it has an attached property Grid.Row

As we said earlier, they are set by a setValue Method, here in Grid class that method is SetRow()

Let's create an attached property, and show the name of the button on the messagebox.
Go to code-behind of your MainWindow.xaml.cs and add this attached property syntax: as you can see there are 2 methods acting as a getter & setter. Our property is an dependency property.
- public static string GetButtonTextProperty(DependencyObject obj)
- {
- return (string)obj.GetValue(ButtonTextProperty);
- }
- public static void SetButtonTextProperty(DependencyObject obj, string value)
- {
- obj.SetValue(ButtonTextProperty, value);
- }
- // Using a DependencyPropertyExample as the backing store for MyProperty. This enables animation, styling, binding, etc...
- public static readonly DependencyProperty ButtonTextProperty =
- DependencyProperty.RegisterAttached("SetButtonText", typeof(string), typeof(MainWindow), new PropertyMetadata());
- private void ButtonSubmit_Click(object sender, RoutedEventArgs e)
- {
- UIElement uIElement = (UIElement)sender;
- MessageBox.Show("Button text is: " + GetButtonTextProperty(uIElement), "Attached Property");
- }


Join the conversation! Your thoughts help the community grow.