[CV][Android] fails to disconnect handlers when items are removed or DataTemplateSelector switches templates
- Dominant language
- C#
- Stars
- 23.3k
- Forks
- 2k
- Avg merge
- 1d 10h
- Merged PRs (30d)
- 297
Description
### Description
When items are removed from a `CollectionView`, or when a `DataTemplateSelector` switches templates (making certain item templates no longer active), the handlers for controls within those templates are not properly disconnected. This results in memory leaks as the controls and their handlers remain in memory.
**Scenario 1: DataTemplateSelector switching templates**
1. Create a `CollectionView` with a `DataTemplateSelector` that switches between two templates based on item state
2. Initially render some items with Template A
3. Change the item state so all items now use Template B (Template A is no longer used)
4. Observe that handlers for controls in Template A instances remain connected
**Scenario 2: Removing items from CollectionView**
1. Create a `CollectionView` with items
2. Remove items from the `ObservableCollection` (using `RemoveAt()`, `Remove()`, or `Clear()`)
3. Observe that handlers for controls in the removed items remain connected
### Expected Behavior
When a CollectionView item is removed or its template is no longer used, all handlers for controls within that item's template should be automatically disconnected via `OnHandlerChanged()` being called with a null handler.
### Actual Behavior
Handlers remain connected indefinitely. The controls remain in memory and cannot be garbage collected, leading to memory leaks. Only recently created items have their handlers disconnected; older items keep their handlers connected.

### Steps to Reproduce
1. Clone https://github.com/Vetle444/MauiTestApp/tree/collectionViewItemHandler
2. Make sure to be on branch collectionViewItemHandler
3. Build and deploy app
4. Navigate to `CollectionView Template Handler Test`
5. Click "Switch to all Template B"
6. Navigate back
7. Click `Show Labels With Connected Handlers`
8. Observe that the items that were removed did not have their handler disconnected
### Link to public reproduction project repository
https://github.com/Vetle444/MauiTestApp/tree/collectionViewItemHandler
### Version with bug
9.0.110 SR12
### Is this a regression from previous behavior?
Yes, this used to work in Xamarin.Forms
### Last version that worked well
_No response_
### Affected platforms
Android
### Affected platform versions
_No response_
### Did you find any workaround?
Some way to disconnect it manually
### Relevant log output
```shell
```
Contributor guide
Assessment
This issue has not been assessed yet.