WPF: Accessing attached properties

This entry is part 51 of 54 in the series Learn WPF

In the example below, the Canvas.Left and Canvas.Top are attached properties.

Now let’s try changing these properties in code. When the repeat button is clicked, let’s move the rectangle a little bit to the right.

The RepeatButton class represents a control that is similar to a Button.  The RepeatButton fires its Click event repeatedly from the time it is pressed until it is released.

<Window x:Class="Attached.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <RepeatButton Click="RepeatButton_Click" Content="Move" Width="80"/>


using System.Windows;
using System.Windows.Controls;

namespace Attached
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        private void RepeatButton_Click(object sender, RoutedEventArgs e)
            // Canvas.SetLeft(rect, 50);
            Canvas.SetLeft(rect, Canvas.GetLeft(rect) + 5);

We can access the Canvas.Left using Canvas.SetLeft(rect, 100).

However, for our case here, we want the rectangle to move to the right repeatly as long as we are clicking on the button.  The code that we are using is:

Canvas.SetLeft(rect, Canvas.GetLeft(rect) + 5);



WPF: Attached property

This entry is part 50 of 54 in the series Learn WPF

We have gone through an example on Dependency Property and unlike Dependency Property, attached property is meant for use in XAML.

One purpose of an attached property is to allow different child elements to specify unique values for a property that is actually defined in a parent element.

In XAML, they are always defined by using the syntax AttachedPropertyProvider.PropertyName

Consider the following example.

  <CheckBox DockPanel.Dock="Top">Hello</CheckBox>

DockPanel.Dock is an attached property of DockPanel.  With DockPanel.Dock, we can inform the DockPanel how we should postition the CheckBox.