Thomas's profileBlogsBlogLists Tools Help

Blog


    03 February

    WPF AttachedProperties

    An AttachedProperty is similar to a DependencyProperty, except that the owner of the value is not the UIElement itself but an external UIElement. For instance, the Canvas.Left and Canvas.Top are AttachedProperties.
     
     
    In Xaml, you usually assign an AttachedProperty the following way:

    <Button Canvas.Left="12" Canvas.Top="44">ButtonText<Button>

     
    Now if you want to create an own AttachedProperty, you simply use the propdp code snippet to create a DependencyProperty first:

    public int Order
    {
         get { return (int)GetValue(OrderProperty); }
        set { SetValue(OrderProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Order. This enables animation, styling, binding, etc...
    public static readonly DependencyProperty OrderProperty =
        DependencyProperty.Register("Order", typeof(int), typeof(MyContainer), new UIPropertyMetadata(0));

     
    To change the DependencyProperty to an AttachedProperty, simply replace DependencyProperty.Register to DependencyProperty.RegisterAttached.
     
    But if you try to attach this Property to a control, it doesn't work!
    You need to Add static Getters and Setters instead of the local "Offset properties in the following way:

    public static int GetOrder(UIElement e)
    {
        if (e == null) throw new ArgumentNullException("e");
        return (int)e.GetValue(OrderProperty);
    }

    public static void SetOrder(UIElement e, int value)
    {
        if (e == null) throw new ArgumentNullException("e");
        e.SetValue(OrderProperty, value);
    }
     
     
    And finally, you have created an AttachedProperty you can use with other Controls.
     
    Here is the complete code:

    [

    ContentProperty("Items")]
    public class MyContainer : ItemsControl
    {
        static MyContainer()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
    typeof(MyContainer), new FrameworkPropertyMetadata(typeof(MyContainer)));
        }

        public static int GetOrder(UIElement e)
        {
            if (e == null) throw new ArgumentNullException("e");
           
    return (int)e.GetValue(OrderProperty);
        }

        public static void SetOrder(UIElement e, int value)
        {
            if (e == null) throw new ArgumentNullException("e");
            e.SetValue(OrderProperty, value);
        }

        // Using a DependencyProperty as the backing store for Order. This enables animation, styling, binding, etc...
       
    public static readonly DependencyProperty OrderProperty =
            DependencyProperty.RegisterAttached("Order", typeof(int), typeof(MyContainer), new FrameworkPropertyMetadata((int)0));
        }

     

    Now you can use it the following way:

    <

    Window x:Class="AttachedProp.Window1"
        xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
        xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
        xmlns:m="clr-namespace:AttachedProp"
       
    Title="Window1" Height="300" Width="300">
       
    <Grid>
            <m:MyContainer>
                <Button Canvas.Bottom="3" m:MyContainer.Order="3">OK</Button>
           
    </m:MyContainer>
        </Grid>
    </
    Window>

     

    Now if you want to use the AttachedProperty within  a ControlTemplate you cannot simply use TemplateBinding. The following snippet shows the correct syntax.

     

    <Style TargetType="{x:Type local:MyControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyControl}">
                    <Border Background="{TemplateBinding Background}" Height="40"
                                 BorderBrush="{TemplateBinding BorderBrush}"
                                 BorderThickness="{TemplateBinding BorderThickness}">
                          <TextBlock Text="{Binding Path=(local:MyContainer.Order), RelativeSource={RelativeSource TemplatedParent}}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    Notice the surrounding bracket on the Path property which is mandantary as well as the appearance of Path. Thus you cannot use the following shortcut:

    <

    TextBlock Text="{Binding local:MyContainer.Order RelativeSource={RelativeSource TemplatedParent}}" Background="Red" MinHeight="24" />

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://thomasgerber.spaces.live.com/blog/cns!58B30559C82E269C!677.trak
    Weblogs that reference this entry
    • None