简体   繁体   English

如何在Xamarin.Forms中使用XAML子集类CachingStrategy对ListView进行子类化

[英]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. 我在XAML文件中设置了我自己的ListView继承子类的CachingStrategy

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 . 但是因为CachingStrategy有一个私有的setter,并且因为它是在其中一个构造函数中使用Parameter属性设置的,由于某种原因它被声明为内部和密封,似乎没有办法子类化ListView

The following compiler error is generated: 生成以下编译器错误:

No property, bindable property, or event found for 'CachingStrategy', or mismatching type between value and property. 没有找到“CachingStrategy”的属性,可绑定属性或事件,或者值和属性之间的类型不匹配。

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 ? Parameter属性是内部的原因是什么,更重要的是,是否有一种简洁的方法来继承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);
    }
}

It is possible to subclass ListView and set the caching strategy from XAML, but it isn't straightforward. 可以将ListView子类化并从XAML设置缓存策略,但这并不简单。 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 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: ListView的子类和从XAML使用的相关代码片段是从Xamarin文档中复制的:

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

Then consuming that in your XAML: 然后在你的XAML中消费它:

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

Not as elegant as when using the base class, sadly. 遗憾的是,它并不像使用基类那样优雅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM