/// <summary> /// Gets the <see cref="BehaviorCollection"/> associated with a specified object. /// </summary> /// <param name="obj">The object from which to retrieve the <see cref="BehaviorCollection"/>.</param> /// <returns>A <see cref="BehaviorCollection"/> containing the behaviors associated with the specified object.</returns> public static BehaviorCollection GetBehaviors(DependencyObject obj) { BehaviorCollection behaviorCollection = (BehaviorCollection)obj.GetValue(Interaction.BehaviorsProperty); if (behaviorCollection == null) { behaviorCollection = new BehaviorCollection(); obj.SetValue(Interaction.BehaviorsProperty, behaviorCollection); } return(behaviorCollection); }
/// <summary> /// This adds the behavior to an image through an attached property. /// </summary> /// <param name="dpo"></param> /// <param name="e"></param> private static void OnIsActiveChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e) { BehaviorCollection bc = Interaction.GetBehaviors(dpo); if (Convert.ToBoolean(e.NewValue)) { bc.Add(new AutoDisabledImageBehavior()); } else { var behavior = bc.FirstOrDefault(beh => beh.GetType() == typeof(AutoDisabledImageBehavior)); if (behavior != null) { bc.Remove(behavior); } } }
/// <exception cref="InvalidOperationException">Cannot host the same BehaviorCollection on more than one object at a time.</exception> private static void OnBehaviorsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { BehaviorCollection oldCollection = (BehaviorCollection)args.OldValue; BehaviorCollection newCollection = (BehaviorCollection)args.NewValue; if (oldCollection != newCollection) { if (oldCollection != null && ((IAttachedObject)oldCollection).AssociatedObject != null) { oldCollection.Detach(); } if (newCollection != null && obj != null) { if (((IAttachedObject)newCollection).AssociatedObject != null) { throw new InvalidOperationException("Error Message"); } newCollection.Attach(obj); } } }