Xamarin Forms Изменение цвета фона каждой видовой ячейки в ListView - PullRequest
0 голосов
/ 26 января 2019

У меня есть время резервирования в listView, например, 8:00, 9:00 и т. Д. Через JSON я получаю резервирования из удаленной БД, которые уже сделаны.Поэтому я хочу изменить цвет фона каждой ячейки (метки) на красный, который зарезервирован, а остальное на зеленый (бесплатные встречи).

Это мой код xaml:

    <StackLayout>
    <ListView x:Name="ItemsListView"
            ItemsSource="{Binding Items}"
            VerticalOptions="FillAndExpand"
            HasUnevenRows="true"
            RefreshCommand="{Binding LoadItemsCommand}"
            IsPullToRefreshEnabled="true"
            IsRefreshing="{Binding IsBusy, Mode=OneWay}"
            CachingStrategy="RecycleElement"
            ItemSelected="OnItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Padding="10">
                        <Label Text="{Binding Text}" 
                            LineBreakMode="NoWrap" 
                            Style="{DynamicResource ListItemTextStyle}" 
                            FontSize="16" />

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

ListViewзаполняется из модели, как:

new Termin { Id = Guid.NewGuid().ToString(), Text = "12:00", Description="" },

Так как я могу изменить цвет этих ячеек?

Псевдокод того, что я хочу:

for(int i=0; i< number of items in the listview; i++) {
if(reservations.contains(listview.itemAt(i)) {
//change background color of viewcell (label?) at position i
}
}

1 Ответ

0 голосов
/ 26 января 2019

(как прокомментировал Бруно)

Добавьте логическое свойство IsReserved к вашей модели:

public class Termin
{
    public string Id { get; set; }
    public string Text { get; set; }
    public string Description { get; set; }
    public bool IsReserved { get; set; }
}

IValueConverter, который возвращает Red, если IsReserved истинно:

public class IsReservedToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value ? Color.Red : Color.Transparent);
    }

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

Добавьте пространство имен вашего IValueConverter:

xmlns:local="clr-namespace:SameNameSpace;assembly=SomeAssemblyName"   

Добавьте IValueConverter к вашему ContentPage.Resources

<ContentPage.Resources>
    <ResourceDictionary>
        <local:IsReservedToColorConverter x:Key="IsReservedToColor"></local:IsReservedToColorConverter>
    </ResourceDictionary>
</ContentPage.Resources>

Использовать конвертер в вашей привязке

<Frame BackgroundColor = "{Binding IsReserved, Converter={StaticResource IsReservedToColor}}">

Окончательный пример XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Forms_31_1.ListPage"
    xmlns:local="clr-namespace:Forms_31_1;assembly=Forms_31_1" >
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IsReservedToColorConverter x:Key="IsReservedToColor"></local:IsReservedToColorConverter>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="listView" BackgroundColor="Aqua" SeparatorColor="Red">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame BackgroundColor = "{Binding IsReserved, Converter={StaticResource IsReservedToColor}}">
                            <StackLayout Orientation="Vertical">
                                <Label Text="{Binding Text}" />
                                <Label Text="{Binding Description}" />
                            </StackLayout>
                        </Frame>
                </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

Вывод:

enter image description here

posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "11:00" });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "12:00", IsReserved = true });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "13:00" });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "14:00" });
...