Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass a ListView with XAML set CachingStrategy in Xamarin.Forms

I am setting the CachingStrategy of my own ListView inherited subclass in a XAML file.

But because the CachingStrategy has a private setter and because it is set using the Parameter attribute in one of it's constructors, which for some reason is declared as internal and sealed, there seems to be no way to subclass a ListView.

The following compiler error is generated:

No property, bindable property, or event found for 'CachingStrategy', or mismatching type between value and property.

Is this intentional? What's the reason for the Parameter attribute to be internal and more importantly, is there a clean way to subclass a ListView?

As a workaround, I ended up doing the following, which works:

public class MyListView : ListView
{
    public new ListViewCachingStrategy CachingStrategy
    {
        get => base.CachingStrategy;
        set => GetType().BaseType.GetProperty(nameof(CachingStrategy))
                        .SetValue(this, value);
    }
}
like image 808
lauxjpn Avatar asked Dec 13 '22 18:12

lauxjpn


1 Answers

It is possible to subclass ListView and set the caching strategy from XAML, but it isn't straightforward. The documentation is here on it:

https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/performance/#Setting_the_Caching_Strategy_in_a_Subclassed_ListView

The important thing is that the caching strategy must be passed into the constructor, which is probably why there is no way to set it using a property.

The relevant pieces of code to subclass ListView and use from XAML are copied from the Xamarin docs here:

public class CustomListView : ListView
{
  public CustomListView (ListViewCachingStrategy strategy) : base (strategy)
  {
  }
  ...
}

Then consuming that in your XAML:

<local:CustomListView>
  <x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
  </x:Arguments>
</local:CustomListView>

Not as elegant as when using the base class, sadly.

like image 192
DavidS Avatar answered May 23 '23 15:05

DavidS