title: Automatically calling OnDetaching() for Silverlight Behaviors
body: <p>I am using several Blend behaviors and triggers on a silverlight control. I am wondering if there is any mechanism for automatically detaching or ensuring that OnDetaching() is called for a behavior or trigger when the control is no longer being used (i.e. removed from the visual tree).</p>
  
  <p>My problem is that there is a managed memory leak with the control because of one of the behaviors. The behavior subscribes to an event on some long-lived object in the OnAttached() override and should be unsubscribing from that event in the OnDetaching() override so that it can become a candidate for garbage collection. However, OnDetaching() never seems to be getting called when I remove the control from the visual tree... the only way I can get it to happen is by explicitly detaching the problematic behaviors BEFORE removing the control and then it is properly garbage collected.</p>
  
  <p>Right now my only solution was to create a public method in the code-behind for the control that can go through and detach any known behaviors that would cause garbage collection problems. It would be up to the client code to know to call this before removing the control from the panel. I don't really like this approach, so I am looking for some automatic way of doing this that I am overlooking or a better suggestion.</p>
  
  <pre><code>public void DetachBehaviors()
  {
       foreach (var behavior in Interaction.GetBehaviors(this.LayoutRoot))
       {
            behavior.Detach();
       }
  
       //continue detaching all known problematic behaviors on the control....
  }
  </code></pre>