WPF: Accessing attached properties

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.

MainWindow.xaml
<Window x:Class="Attached.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas>
        <RepeatButton Click="RepeatButton_Click" Content="Move" Width="80"/>
        <Rectangle 
            Name="rect" 
            Canvas.Top="60" 
            Canvas.Left="60" 
            Width="150" 
            Height="150" 
            Fill="Yellow"/>
    </Canvas>
</Window>

 

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

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

        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);

 

 

Series Navigation<< WPF: Attached property
WPF: Creating ellipse or rectangle using canvas >>