This repository has been archived by the owner on May 1, 2024. It is now read-only.
Automatically detaching behaviors #14866
Unanswered
EmmanuelJego
asked this question in
Q&A
Replies: 2 comments
-
I too would like to know the answer to this. At first glance it seems a pretty clean way to do it. (I'm also curious why Behaviors are not automatically removed). |
Beta Was this translation helpful? Give feedback.
0 replies
-
I think there is also more info and discussion about that for .NET MAUI: dotnet/maui#3968 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello!
This issue is more of a question than a bug report.
We are currently using several
Behaviors
within our X.Forms project, to do different things onVisualElement
s. We recently noticed that behaviors are not detached from their associated control automatically when the control is destroyed. Which seems normal according to the documentation (https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating#removing-a-behavior-from-a-control).If we do not do that, the behavior is never destroyed, and the
OnDetachingFrom
method is not called. Which can leads to memory leaks.To avoid that, we have to clear explicitly (manually) the
Behaviors
collection for each of our controls that have behaviors, for instance when the parent's pageOnDisappearing
method is called. But it seems very laborious, and in some cases it does not work: if the control that has behavior(s) is removed before the page disappears (a list item deletion for instance).Now, to do that automatically, we built a class that inherits from
Xamarin.Forms.Behavior<T>
in which we override theOnAttachedTo
method, to add aLifecycleEffect
(from the Xamarin.CommunityToolkit) to the attached control. When theUnloaded
event is raised, we can now clear theBehaviors
collection of the control. All of our behaviors have to inherit from that class obviously.It works, but we were wondering if this is right way to do it. We do not clearly understand why the behaviors are not automatically detached from the associated control when it is destroyed.
Is there something that we are missing? Or a better way to do it?
Thanks in advance for your help!
Emmanuel
Beta Was this translation helpful? Give feedback.
All reactions