5

In Silverlight 3.0 I have added a custom behavior to some UIElement in Code Behind.

I wanted to remove the Behavior later in runtime.

What is the C# syntax to Detach an already added Behavior from an UIElement?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
kanchirk
  • 912
  • 2
  • 13
  • 29

1 Answers1

8

I am guessing you are talking about a behavior deriving from the Behavior<T> class in the Blend SDK...

Do you still have a reference to the behavior from when you attached it?

MyCustomBehavior myBehavior = new MyCustomBehavior();
myBehavior.Attach(myElement);
...
myBehavior.Detach();

EDIT

If you no longer have a reference to the instance of the behavior when you want to detach it you can do something like this to detach all behaviors on a DependencyObject:

foreach (var behavior in Interaction.GetBehaviors(myElement))
{
    behavior.Detach();
}
Dan Auclair
  • 3,607
  • 25
  • 32
  • After Detach(), Attach() cannot re-attach or restore the behavior to the dependency object. solution? – KMC Nov 14 '12 at 15:18