2010-08-17 73 views
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)这个元素是它的一个子元素。

在回调的类型signiature:

void Callback(DependencyObject d, DependencyPropertyChagnedEventArgs args)

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

收集对附属属性所属元素的引用的最佳方式是什么?

回答

2

您可以在Visual Tree中查找您的装饰器类型,从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; 
}