复杂附加财产行为

时间:2010-08-17 20:56:33

标签: .net wpf attached-properties

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

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

        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是该属性的实际值。

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

1 个答案:

答案 0 :(得分:2)

从d开始,您可以走向Visual Tree,寻找您的Decorator类型。这是一个可以使用的简单方法:

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