Attached Property in WPF

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(.)
  1. <Grid>      
  2.        <Grid.RowDefinitions>      
  3.            <RowDefinition Height="Auto"/>      
  4.            <RowDefinition Height="Auto"/>      
  5.            <RowDefinition Height="Auto"/>      
  6.        </Grid.RowDefinitions>      
  7.        <StackPanel Orientation="Horizontal" Grid.Row="0">      
  8.        <Label x:Name="LabelUserName"      
  9.            Content="UserName:"       
  10.            VerticalAlignment="Center"       
  11.            Margin="200 0 0 0"    
  12.            />      
  13.        <TextBox x:Name="TextBoxName"       
  14.                 Text="{Binding UserName}"       
  15.                 Height="30"       
  16.                 Width="300"/>      
  17.        </StackPanel>      
  18.        <Button x:Name="ButtonSubmit"       
  19.                Margin="{StaticResource MarginTOP}"       
  20.                Content="Submit"       
  21.                Height="20"       
  22.                Width="100"       
  23.                HorizontalAlignment="Center"       
  24.                VerticalAlignment="Center"      
  25.                Grid.Row="1"/>      
  26.        <TextBlock x:Name="TextBlockUserName"       
  27.                   Text="{Binding UserName}"       
  28.                   Style="{DynamicResource TextBlockBottomStyle}"       
  29.                   HorizontalAlignment="Center"       
  30.                   VerticalAlignment="Top"       
  31.                   Grid.Row="2"/>      
  32.    </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.
  1. public static string GetButtonTextProperty(DependencyObject obj)  
  2. {  
  3.     return (string)obj.GetValue(ButtonTextProperty);  
  4. }  
  5.   
  6. public static void SetButtonTextProperty(DependencyObject obj, string value)  
  7. {  
  8.     obj.SetValue(ButtonTextProperty, value);  
  9. }  
  10.   
  11. // Using a DependencyPropertyExample as the backing store for MyProperty.  This enables animation, styling, binding, etc...  
  12. public static readonly DependencyProperty ButtonTextProperty =  
  13.     DependencyProperty.RegisterAttached("SetButtonText"typeof(string), typeof(MainWindow), new PropertyMetadata()); 
 We need to add to the button click event, so let's go ahead and add that event in the same code-behind as well.
  1. private void ButtonSubmit_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             UIElement uIElement = (UIElement)sender;  
  4.             MessageBox.Show("Button text is: " + GetButtonTextProperty(uIElement), "Attached Property");  
  5.         } 
Lastly, we need to call our newly created attached property from XAML.
 
Open Mainwindow.xaml and spot bold code.
 
You can see in the control button we have added our newly attached property named ButtonTextProperty. We are setting it's value to Submit, so when you click on the submit button you get popup showing submitted text.
  1. <Window x:Class="DependencyPropertyExample.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
  4.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.         xmlns:local="clr-namespace:DependencyPropertyExample"    
  7.         mc:Ignorable="d"    
  8.         Title="MainWindow" Height="450" Width="800">    
  9.     <Window.Resources>    
  10.         <Style x:Key="TextBlockBottomStyle" BasedOn="{StaticResource {x:Type TextBlock}}"    
  11.                TargetType="TextBlock">    
  12.             <Style.Setters>    
  13.                 <Setter Property="FontSize" Value="40"/>    
  14.                 <Setter Property="FontStyle" Value="Italic"/>    
  15.             </Style.Setters>    
  16.         </Style>    
  17.         <Thickness x:Key="MarginTOP">0 5 0 0</Thickness>    
  18.     </Window.Resources>    
  19.     <Grid>    
  20.         <Grid.RowDefinitions>    
  21.             <RowDefinition Height="Auto"/>    
  22.             <RowDefinition Height="Auto"/>    
  23.         </Grid.RowDefinitions>    
  24.         <StackPanel Orientation="Horizontal">          
  25.         <Button x:Name="ButtonSubmit"     
  26.                 Click="ButtonSubmit_Click"    
  27.                 Margin="{StaticResource MarginTOP}"     
  28.                 local:MainWindow.ButtonTextProperty="Submit"    
  29.                 Content="Submit"     
  30.                 Height="20"     
  31.                 Width="100"     
  32.                 HorizontalAlignment="Center"     
  33.                 VerticalAlignment="Center"    
  34.                 Grid.Row="1"/>            
  35.     </Grid>    
  36. </Window>    
Go ahead and run your project. Click on submit button and you'll get this output.
 
There you go, our newly created attached property is working as expected.
 
MainWindow.xaml.cs for your reference:
  1. using System.Windows;  
  2.   
  3. namespace DependencyPropertyExample  
  4. {  
  5.     /// <summary>  
  6.     /// Interaction logic for MainWindow.xaml  
  7.     /// </summary>  
  8.     public partial class MainWindow : Window  
  9.     {  
  10.         public MainWindow()  
  11.         {  
  12.             InitializeComponent();  
  13.             this.DataContext = new MainWindowViewModel();  
  14.         }  
  15.         public static string GetButtonTextProperty(DependencyObject obj)  
  16.         {  
  17.             return (string)obj.GetValue(ButtonTextProperty);  
  18.         }  
  19.   
  20.         public static void SetButtonTextProperty(DependencyObject obj, string value)  
  21.         {  
  22.             obj.SetValue(ButtonTextProperty, value);  
  23.         }  
  24.   
  25.         // Using a DependencyPropertyExample as the backing store for MyProperty.  This enables animation, styling, binding, etc...  
  26.         public static readonly DependencyProperty ButtonTextProperty =  
  27.             DependencyProperty.RegisterAttached("SetButtonText"typeof(string), typeof(MainWindow), new PropertyMetadata());  
  28.   
  29.         private void ButtonSubmit_Click(object sender, RoutedEventArgs e)  
  30.         {  
  31.             UIElement uIElement = (UIElement)sender;  
  32.             MessageBox.Show("Button text is: " + GetButtonTextProperty(uIElement), "Attached Property");  
  33.         }  
  34.     }  

I hope your questions have been cleared about the attached property. Feel free to connect if you have any doubts. Happy coding!