private static void OnBehaviorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { BehaviorCollection oldBehaviors = (BehaviorCollection)e.OldValue; if (oldBehaviors != null && ((IAttachedObject)oldBehaviors).AssociatedObject == d) { oldBehaviors.Detach(); } BehaviorCollection newBehaviors = (BehaviorCollection)e.NewValue; if (newBehaviors != null) { FrameworkElement element = FrameworkElement.FindTreeElement(newBehaviors); if (element != null && !element.IsInitialized) { // assigned from a template, collection must be cloned d.SetValue(BehaviorsProperty, newBehaviors.Clone()); } else { newBehaviors.Attach(d); } } }