views:

18

answers:

1

I've got an object (Decorator) that defines an attached property for any of it's children.

So far I have no issue setting/getting the attached property on the remote object:

        public static readonly DependencyProperty RequiresRoleProperty =
            DependencyProperty.RegisterAttached("RequiresRole", typeof (string), typeof (UIElement),
                                                new FrameworkPropertyMetadata(
                                                    null,
                                                    FrameworkPropertyMetadataOptions.AffectsRender,
                                                    OnSetRequiresRole));
        [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants=true)]
        public static string GetRequiresRole(UIElement element)
        {
            return element.GetValue(RequiresRoleProperty) as string;
        }

        public static void SetRequiresRole(UIElement element, string val)
        {
            element.SetValue(RequiresRoleProperty, val);
        }

However, I've got an OnSetCallback set up for this attached property to so my setup logic, however I need a reference to the decorator(MyClass) this element is a child of.

In the type signiature of the callback:

void Callback(DependencyObject d, DependencyPropertyChagnedEventArgs args)

  • d Is the object for which the attached property is set.
  • args.NewValue & args.OldValue is the actual value of the property.

What's the best way of collecting a reference to the containing element that the attached property belongs to?

+1  A: 

You can walk up the Visual Tree looking for your Decorator type, starting at d. This is a simple method you can use:

public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class
{
    DependencyObject target = dependencyObject;
    do
    {
        target = VisualTreeHelper.GetParent(target);
    }
    while (target != null && !(target is T));
    return target as T;
}
John Bowen