Listview не отображает ячейку просмотра, пока не прокрутит обратно к представлению

Listview не отображает элемент списка при переходе к нему. Если я начну прокручивать, все элементы станут видны. Я проверил INotityPropertyChanged для моделей, а также для списка (Itemsource для просмотра списка). Код XAML для просмотра списка `

<ListView x:Name="HospitalResultListView" CachingStrategy="RecycleElement"                 
                          SeparatorVisibility="None"
                          ItemsSource="{Binding HospitalList}" VerticalOptions="FillAndExpand"
                          RowHeight="150" ItemTapped="HospitalResultListView_ItemTapped"  >

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <local:HospitalListViewVC Address="{Binding Address}" Name="{Binding Name}" Type="{Binding Type}" Rate="{Binding Rate}" Distance="{Binding Distance}" HospitalImageURL="{Binding HospitalImageURL}" />
                    </DataTemplate>
                </ListView.ItemTemplate>

            </ListView>

`

и код просмотра ячеек `

class HospitalListViewVC : ViewCell
    {
        Label addressLabel, distanceLabel, typeLabel, rateLabel, nameLabel;
        Image hospitalImage;
        CachedImage cachedImage = null;

        #region Bindable properties
        public static readonly BindableProperty HospitalImageURLProperty =
            BindableProperty.Create(nameof(HospitalModel.HospitalImageURL), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string HospitalImageURL
        {
            get { return (string)GetValue(HospitalImageURLProperty); }
            set { SetValue(HospitalImageURLProperty, value); }
        }

        public static readonly BindableProperty AddressProperty =
            BindableProperty.Create(nameof(HospitalModel.Address), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string Address
        {
            get { return (string)GetValue(AddressProperty); }
            set { SetValue(AddressProperty, value); }
        }

        public static readonly BindableProperty DistanceProperty =
            BindableProperty.Create(nameof(HospitalModel.Distance), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string Distance
        {
            get { return (string)GetValue(DistanceProperty); }
            set { SetValue(DistanceProperty, value); }
        }

        public static readonly BindableProperty TypeProperty =
            BindableProperty.Create(nameof(HospitalModel.Type), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string Type
        {
            get { return (string)GetValue(TypeProperty); }
            set { SetValue(TypeProperty, value); }
        }

        public static readonly BindableProperty RateProperty =
            BindableProperty.Create(nameof(HospitalModel.Rate), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string Rate
        {
            get { return (string)GetValue(RateProperty); }
            set { SetValue(RateProperty, value); }
        }

        public static readonly BindableProperty NameProperty =
            BindableProperty.Create(nameof(HospitalModel.Name), typeof(string), typeof(HospitalListViewVC), null, BindingMode.OneWay);
        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }
        #endregion

        #region constructor
        public HospitalListViewVC()
        {
            var grid = new Grid
            {
                Margin = new Thickness(10),

                BackgroundColor = Color.FromHex("#00FFFF"),
                IsClippedToBounds = true,
                ColumnDefinitions = {
                    new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
                }
            };

            cachedImage = new CachedImage { Aspect = Aspect.AspectFill};
            nameLabel = new Label();

            addressLabel = new Label();
            distanceLabel = new Label();
            typeLabel = new Label();
            rateLabel = new Label();
            var informationStack = new StackLayout { Padding = new Thickness(5) };
            informationStack.Children.Add(addressLabel);
            informationStack.Children.Add(distanceLabel);
            informationStack.Children.Add(typeLabel);
            informationStack.Children.Add(rateLabel);

            grid.Children.Add(cachedImage, 0, 0);
            grid.Children.Add(nameLabel, 0, 0);
            grid.Children.Add(informationStack, 1, 0);

            View = grid;
        }

        #endregion

        #region Bindings

        protected override void OnBindingContextChanged()
        {
            cachedImage.Source = null;
            base.OnBindingContextChanged();

            if (BindingContext != null)
            {
                cachedImage.Source = HospitalImageURL;
                addressLabel.Text = Address;
                distanceLabel.Text = Distance;
                typeLabel.Text = Type;
                rateLabel.Text = Rate;
                nameLabel.Text = Name;
            }
        }
        #endregion
    }`

любой указатель будет действительно полезен.

Прикрепите GIF-файл эмулятора Android, чтобы лучше понять проблему. >


person niketan    schedule 02.10.2018    source источник


Ответы (2)


у меня была такая же проблема сегодня. Проблема в том, что iOS отображает ListView иначе, чем Android.

Создайте собственный ListView, который расширяет обычный ListView, и вставьте следующий код.

public class ListView : Xamarin.Forms.ListView
{
    public ListView() : this(Device.RuntimePlatform == Device.Android ? ListViewCachingStrategy.RecycleElement : ListViewCachingStrategy.RetainElement)
    {
    }

    public ListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
    {
    }

}

А затем используйте свой собственный ListView на странице Xaml.

Разница вот в чем:

public ListView() : this(Device.RuntimePlatform == Device.Android ? ListViewCachingStrategy.RecycleElement : ListViewCachingStrategy.RetainElement)

Я надеюсь, что это решение для вас!

С уважением, Ник

person Nick Hoffmann    schedule 19.10.2018
comment
Я пробовал все эти возможные решения. :) Проблема была с версией форм Xamarin. Я использовал бета-версию для некоторых требований к плагину. Я удалил этот плагин и восстановил стабильную версию, и список начал отображаться нормально. - person niketan; 05.11.2018

https://github.com/xamarin/Xamarin.Forms/issues/6810

нашел этот пост при поиске решения, похоже, они исправили это в выпуске Xamarin.Forms 4.0.0/4.1.0

person kisslory    schedule 13.08.2019