Визуальная проблема с ListView при использовании конвертера, чтобы сделать метки жирными - PullRequest
0 голосов
/ 23 февраля 2019

У меня есть ListView, связанный с ObservableCollection.Я создал ValueConverter, который оценивает, если строковое свойство имеет определенное значение, устанавливает для FontAttribute значение Bold соответствующих меток в ListItem.Хотя иногда, когда я обновляю ObservableCollection, некоторые элементы не изменяются с жирного на обычный.Если я прокручиваю ListView вниз, они обновляются.

Мой просмотр списка CachingStrategy устанавливается в RecycleElement, потому что когда я устанавливаю его в RetainElement, у меня возникают некоторые проблемы с элементами, отображающими неверные данные.

Есть ли у кого-нибудь какие-либоИдея, почему это происходит?

Это код ListView.

<ListView
x:Name="NewList"
CachingStrategy="RecycleElement"
HasUnevenRows="True"
IsPullToRefreshEnabled="False"
ItemsSource="{Binding Notifications}"
SelectionMode="None">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell Height="60">
            <Grid
                ColumnSpacing="0"
                HeightRequest="60"
                RowSpacing="0">
                <BoxView BackgroundColor="#bd3826" HorizontalOptions="Fill" />
                <Grid
                    BackgroundColor="White"
                    ColumnSpacing="0"
                    HeightRequest="60"
                    RowSpacing="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="40" />
                        <ColumnDefinition Width="60*" />
                        <ColumnDefinition Width="40*" />
                        <ColumnDefinition Width="40" />
                    </Grid.ColumnDefinitions>

                    <Grid.GestureRecognizers>
                        <PanGestureRecognizer PanUpdated="PanGestureRecognizer_PanUpdated" />
                        <TapGestureRecognizer Command="{Binding BindingContext.TapNewCommand, Source={x:Reference NewList}}" CommandParameter="{Binding .}" />
                    </Grid.GestureRecognizers>

                    <Image
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="0"
                        HeightRequest="25"
                        HorizontalOptions="Center"
                        Source="{Binding OrderItemTypeUrl}"
                        VerticalOptions="Center"
                        WidthRequest="25" />
                    <Label
                        Grid.Row="0"
                        Grid.Column="1"
                        FontAttributes="{Binding NotificationStatus, Converter={StaticResource TypeBold}}"
                        FontSize="16"
                        Text="{Binding MaterialDescription}"
                        TextColor="#4c4c4c" />
                    <Label
                        Grid.Row="0"
                        Grid.Column="2"
                        FontAttributes="{Binding NotificationStatus, Converter={StaticResource TypeBold}}"
                        FontSize="16"
                        Text="{Binding SoDate, StringFormat='{}{0:dd.MM.yyyy HH\\:mm}'}"
                        TextColor="#4c4c4c" />
                    <Label
                        Grid.Row="1"
                        Grid.Column="1"
                        Grid.ColumnSpan="2"
                        FontAttributes="{Binding NotificationStatus, Converter={StaticResource TypeBold}}"
                        FontSize="16"
                        TextColor="#4c4c4c">
                        <Label.FormattedText>
                            <FormattedString>
                                <Span Text="{Binding IBaseAddressStreet}" />
                                <Span Text=", #" />
                                <Span Text="{Binding IBaseAddressHouseNumber}" />
                                <Span Text=", " />
                                <Span Text="{Binding IBaseAddressZipCode}" />
                                <Span Text=", " />
                                <Span Text="{Binding IBaseAddressHouseCity}" />
                            </FormattedString>
                        </Label.FormattedText>
                    </Label>
                    <Label
                        Grid.Row="2"
                        Grid.Column="1"
                        Grid.ColumnSpan="2"
                        FontAttributes="{Binding NotificationStatus, Converter={StaticResource TypeBold}}"
                        FontSize="14"
                        Text="{Binding BusinessPartnerDescription}"
                        TextColor="#4c4c4c" />
                    <Image
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="3"
                        HeightRequest="40"
                        HorizontalOptions="Center"
                        Source="{local:ImageResource ELCO.App.Images.delete.png}"
                        VerticalOptions="Center"
                        WidthRequest="40">
                        <Image.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding BindingContext.DeleteItemCommand, Source={x:Reference NewList}}" CommandParameter="{Binding .}" />
                        </Image.GestureRecognizers>
                    </Image>

                </Grid>
            </Grid>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

Код преобразователя значений

public class BoldConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var isBold = ((string)value) != "READED";
            if (isBold)
            {
                return FontAttributes.Bold;
            }
            else
            {
                return FontAttributes.None;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Методы ViewModel

    public async void GetData()
{
    using (UserDialogs.Instance.Loading(App.AppSession.LocalTranslate.globalLoading))
    {
        try
        {
            Notifications = await App.AppSession.GetNotificationsFromApi();
        }
        catch (Exception ex)
        {
        }
    }
}

private async void OnItemTapped(object obj)
{
    try
    {
        using (UserDialogs.Instance.Loading(App.AppSession.LocalTranslate.globalLoading))
        {
            SelectedNotification = (obj as Notification);
            SelectedNotification.Altered = true;
            SelectedNotification.NotificationStatus = "READED";
            Notifications.Where(x => x.IdNotification == SelectedNotification.IdNotification)
                .ToList().ForEach(u =>
                {
                    u.Altered = true;
                    u.NotificationStatus = "READED";
                });

            await App.AppSession.LocalDB.SaveNotification(SelectedNotification);

            App.AppSession.ActualNotification = SelectedNotification;
            await NavigationService.NavigateAsync("DetailPage");
        }
    }
    catch (Exception ex)
    {
    }
}

public async void FillList()
{
    try
    {
        if (Notifications != null)
        {
            Notifications = new ObservableCollection<Notification>(App.AppSession.GetNotificationsFromDb(););
        }
    }
    catch (Exception ex)
    {
    }
}

Я сделал много тестов, и данные в порядке, но проблема все еще видна.

...