Articles in this section
Category / Section

How to dispose of children of ListView in Xamarin.Forms (SfListView)

1 min read

You can dispose the custom view that was loaded in SfListView.ItemTemplate in Xamarin.Forms SfListView by customizing the ItemGenerator.

C#

Created the custom Editor control in the PCL project that implements IDisposable.

namespace ListViewXamarin
{
    public class CustomEntry : Entry, IDisposable
    {
        public CustomEntry()
        {
            this.Text = "Country";
            BackgroundColor = Color.LightGray;
        }
        
        public void Dispose()
        {
            System.Diagnostics.Debug.WriteLine("custom control disposed");
        }
    }
}

XAML

Add the custom control in the ItemTemplate.

<syncfusion:SfListView x:Name="listView" ItemSize="60" ItemsSource="{Binding ContactsInfo}">
    <syncfusion:SfListView.ItemTemplate >
        <DataTemplate>
            <Grid x:Name="grid">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="70" />
                    <ColumnDefinition Width="250" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Image Source="{Binding ContactImage}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="50" WidthRequest="50"/>
                <Label LineBreakMode="NoWrap" TextColor="#474747" Text="{Binding ContactName}" Grid.Column="1"/>
                <local:CustomEntry Placeholder="Enter here" Grid.Column="2"/>
            </Grid>
        </DataTemplate>
    </syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>

C#

Extend the ItemGenerator and ListViewItem, and override the Dispose method to dispose the custom control.

public class ItemGeneratorExt : ItemGenerator
{
    public SfListView listView;
 
    public ItemGeneratorExt(SfListView listView) : base(listView)
    {
        this.listView = listView;
    }
 
    protected override ListViewItem OnCreateListViewItem(int itemIndex, ItemType type, object data = null)
    {
        if (type == ItemType.Record)
            return new ListViewItemExt(this.listView);
        return base.OnCreateListViewItem(itemIndex, type, data);
    }
}
 
public class ListViewItemExt : ListViewItem
{
    private SfListView listView;
 
    public ListViewItemExt(SfListView listView)
    {
        this.listView = listView;
    }
 
    protected override void Dispose(bool disposing)
    {
        if (this.Content != null)
        {
            var grid = this.Content as Grid;
            var customEntry = (CustomEntry)grid.Children.FirstOrDefault(o => o is CustomEntry);
            customEntry.Dispose();
        }
 
        base.Dispose(disposing);
    }
}

View sample in GitHub

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied