Skip Navigation LinksHome > View Post

Binding to Attached Properties

How can I bind to an attached property in WPF? For example, imagine I want to bind the content of a TextBlock to the left position of an element on a canvas.

<Ellipse x:Name="ellipse" Canvas.Left="20" />
<TextBlock Text="{Binding ElementName=ellipse, Path=Canvas.Top}" />

The Xaml above wouldn't work because the binding will first go looking for a property called Canvas on the ellipse. The solution is easy, wrap the attached property in parentheses.

<Ellipse x:Name="ellipse" Canvas.Left="20" />
<TextBlock Text="{Binding ElementName=ellipse, Path=(Canvas.Top)}" />

Bingo. The same format is used when, for example, you want to target an attached property in an animation. Here's an example that shows both in action.

<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <Page.Resources>
        <Storyboard x:Key="moveRectangle">
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="True" RepeatBehavior="Forever">
                <SplineDoubleKeyFrame KeyTime="00:00:02" Value="500"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Page.Resources>
    <Page.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
            <BeginStoryboard Storyboard="{StaticResource moveRectangle}"/>
        </EventTrigger>
    </Page.Triggers>
    
    <Canvas>
        <Rectangle x:Name="rectangle" Width="33" Height="33" Fill="#FFFF0000" Stroke="#FF000000" Canvas.Left="10" Canvas.Top="10" />
        <TextBlock Text="{Binding ElementName=rectangle, Path=(Canvas.Left)}" />
    </Canvas>
</Page>

Download the xaml file to see for yourself.

Tags: WPF

 
Josh Post By Josh Twist
9:18 AM
30 Oct 2007

» Next Post: Using Binding to position a Collection of elements
« Previous Post: Binding to the Current Item in WPF

Comments are closed for this post.

Posted by Stefan @ 02 Mar 2009 6:28 AM
Thank you, helped me a lot!

Posted by Patrick @ 08 Sep 2009 6:38 PM
thanks for that!

Posted by Shane @ 27 Aug 2010 3:23 PM
Nice one....too easy :)

Posted by thomas @ 10 Feb 2011 6:56 PM
way cool, where did you get this information from? can you hint on a good reference on data binding expressions?

cheers
thomas

© 2005 - 2014 Josh Twist - All Rights Reserved.