Список Xamarin с изображениями не прокручивается плавно

1

Я разрабатываю приложение для блога, в которое я помещал карточку в каждый список предметов. На этих карточках есть этикетки и изображения. Проблема в том, что при загрузке списка просмотра он не прокручивается плавно с изображениями, а мои изображения из URI. Я также использовал последний плагин FFImageLoading, но проблема остается той же. Даже есть дополнительная проблема, этот плагин не кэширует правильное изображение.

Я уже много искал в интернете, и стало казаться, что у ксамарина нет никакого решения для этого. Последняя надежда только на этот вопрос.

Моя страница xaml

<ContentPage.BindingContext>
    <local1:HomeViewModel/>
</ContentPage.BindingContext>
<ListView x:Name="listView" SelectedItem="{Binding SelcetedItem,Mode=TwoWay}" SeparatorVisibility="None"
          RowHeight="150" 
          ItemsSource="{Binding Items}" CachingStrategy="RecycleElement" HasUnevenRows="True"  >

        <ListView.Behaviors>
            <extended:InfiniteScrollBehavior IsLoadingMore="{Binding IsBusy}" />
        </ListView.Behaviors>

        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <local:CardViewTemplate />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

        <ListView.Footer>
            <Grid Padding="6" IsVisible="{Binding IsBusy}">
                <Grid.Triggers>
                    <Trigger TargetType="Grid" Property="IsVisible" Value="False">
                        <Setter Property="HeightRequest" Value="0" />
                    </Trigger>
                </Grid.Triggers>
                <Label Text="Loading..." TextColor="DeepPink" FontSize="20" FontAttributes="Bold" VerticalOptions="Center" HorizontalOptions="Center" />
            </Grid>
        </ListView.Footer>

BindingContext HomeViewModel.cs

public HomeViewModel()
    {
        Items = new InfiniteScrollCollection<HomeDto>
        {
            OnLoadMore = async () =>
            {
                IsBusy = true;

                // load the next page
                var page = Items.Count / PageSize;

                var items = await _dataService.GetItemsAsync(page, PageSize);

                IsBusy = false;

                // return the items that need to be added
                return items;
            },
            OnCanLoadMore = () =>
            {
                return Items.Count < Convert.ToInt32(_dataService.CardDataCollection.Count);
            }
        };

        DownloadDataAsync();
    }

Данные поступают отсюда

 private void GenerateCardModel()
    {
        CardDataCollection = HomeServiceHelper.AllArticles();

        foreach(var item in CardDataCollection)
        {
            item.ImageUrl = "http://192.168.31.204:8080/" + item.ImageUrl;
        }
    }

    public async Task<List<HomeDto>> GetItemsAsync(int pageIndex, int pageSize)
    {
        await Task.Delay(2000);

        return CardDataCollection.Skip(pageIndex * pageSize).Take(pageSize).ToList();
    }

Наконец, мои фреймы (CardViewTemplate.xaml), которые отображают данные в виде списка каждой ячейки

<Frame IsClippedToBounds="True"
     HasShadow="True"
     BackgroundColor="White" CornerRadius="5" Margin="10" >
    <StackLayout Orientation="Horizontal">

        <Grid VerticalOptions="CenterAndExpand" Padding="0" HorizontalOptions="FillAndExpand" BackgroundColor="Transparent">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="20"/>
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="70"/>
            </Grid.ColumnDefinitions>

            <StackLayout Grid.Row="0" Grid.Column="0">
                <Label FontAttributes="None" HorizontalTextAlignment="Start" VerticalTextAlignment="Start" FontSize="18" 
                       FontFamily="Arial" Text="{Binding ArticleHeading, Mode = TwoWay}" LineBreakMode="TailTruncation" TextColor="#212121"
                       MaxLines="3">
                </Label>
            </StackLayout>
            <StackLayout Grid.Row="0" Grid.Column="1" BackgroundColor="Yellow"  WidthRequest="70" HorizontalOptions="EndAndExpand" 
                         VerticalOptions="FillAndExpand">
                <ff:CachedImage Source="{Binding  ImageUrl}" HorizontalOptions="FillAndExpand" CacheType="Memory">
                </ff:CachedImage>
            </StackLayout>

            <StackLayout Grid.Row="1" Grid.Column="0" Orientation="Horizontal">
                <Label FontAttributes="None" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" 
                       FontSize="14" Text="{Binding Admin , Mode = TwoWay}" TextColor="#212121" >
                </Label>
                <Label FontAttributes="None" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" 
                       FontSize="14" Text="{Binding LastModifiedOn , Mode = TwoWay, StringFormat='{0:d}'}" TextColor="Gray" >
                </Label>
            </StackLayout>

        </Grid>
    </StackLayout>
</Frame>
Теги:
xamarin
xamarin.forms
xamarin.android

1 ответ

0

Во-первых, убедитесь, что вашей стратегией кэширования является элемент Recycle в Listview.

Затем, чтобы предотвратить появление изображений в неправильных ячейках, расширьте пользовательскую ячейку просмотра и измените источник вашего изображения. Вы можете проверить официальную документацию.

Смотрите пример:

public class MyCustomCell : ViewCell
{
    readonly CachedImage cachedImage = null;

    public MyCustomCell()
    {
        cachedImage = new CachedImage();
        View = cachedImage;
    }

    protected override void OnBindingContextChanged()
    {
        // you can also put cachedImage.Source = null; here to prevent showing old images occasionally
        cachedImage.Source = null;

        //Cast the respective model.
        var item = BindingContext as Item;

        if (item == null)
        {
            return;
        }

        cachedImage.Source = item.ImageUrl;

        base.OnBindingContextChanged();
    }
}
  • 0
    Стратегия кэширования уже является элементом Recycle в представлении списка.
  • 0
    И вы используете настраиваемую ячейку просмотра в соответствии с моим ответом? ...

Ещё вопросы

Сообщество Overcoder
Наверх
Меню