0

我有一个对象(装饰器),它为它的任何孩子定义了一个附加属性。

到目前为止,我在远程对象上设置/获取附加属性没有问题:

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

但是,我已经为此附加属性设置了 OnSetCallback,因此我的设置逻辑,但是我需要对装饰器(MyClass)的引用,该元素是其子元素。

在回调的类型签名中:

void Callback(DependencyObject d, DependencyPropertyChagnedEventArgs args)

  • d是为其设置附加属性的对象。
  • args.NewValue&args.OldValue是财产的实际价值。

收集对附加属性所属的包含元素的引用的最佳方法是什么?

4

1 回答 1

2

您可以从 d 开始在 Visual Tree 中查找您的装饰器类型。这是您可以使用的简单方法:

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;
}
于 2010-08-17T22:05:19.720 回答