.net 复杂附着属性行为

.net 复杂附着属性行为,.net,wpf,attached-properties,.net,Wpf,Attached Properties,我有一个对象(Decorator),它为它的任何子对象定义一个附加属性 到目前为止,设置/获取远程对象上的附加属性没有问题: public static readonly DependencyProperty RequiresRoleProperty = DependencyProperty.RegisterAttached("RequiresRole", typeof (string), typeof (UIElement),

我有一个对象(Decorator),它为它的任何子对象定义一个附加属性

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

        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,所以我的设置逻辑是这样的,但是我需要一个对这个元素的子元素decorator(MyClass)的引用

在回调的类型符号中:

void回调(DependencyObject d,DependencyPropertyHagnedEventArgs args)

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

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

您可以沿着可视化树查找装饰器类型,从d开始。这是一种可以使用的简单方法:

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;
}
公共静态T FindAncestor(DependencyObject DependencyObject)
T:在哪里上课
{
DependencyObject目标=DependencyObject;
做
{
target=VisualTreeHelper.GetParent(目标);
}
而(target!=null&&!(target是T));
将目标返回为T;
}