XAML .NET MAUI中的ObservableCollection条件颜色绑定

e5njpo68  于 2023-04-18  发布在  .NET
关注(0)|答案(1)|浏览(282)

在.NET MAUI中使用绑定和ObservableCollection,如何有条件地设置GUI元素的BackgroundColor属性?

XAML<Label BackgroundColor="{Binding name.color}"/>
C#if (x) { name.color = Colors.Red; } else { name.color = Colors.Blue; }

或者像这样使用字符串数据:

C#name.color = "#FF0000";不工作。
C#LabelCommonName.BackgroundColor = Colors.Red;

无法使用CollectionView。

我的实际XAML

我省略了页边距、填充、网格定义和其他不相关的样式。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:projectName"
             x:Class="projectName.CalendarPage"
             Title="CalendarPage">
    <Grid>
        <ScrollView>
            <RefreshView x:Name="CalendarRefresh"
                         Refreshing="RefreshCalendar">
                <CollectionView x:Name="CalendarView">
                    <CollectionView.ItemTemplate>
                        <DataTemplate x:DataType="local:Calendar">
                            <Frame>
                                <Grid>
                                    <Label x:Name="LabelCommonName" 
                                           Text="{Binding name.common}"/>
                                    <Label Text="{Binding name.scientific}"/>
                                </Grid>
                            </Frame>
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
            </RefreshView>
        </ScrollView>
    </Grid>
</ContentPage>

我的代码

使用ObservableCollection在向下滚动时添加更多项。

public partial class CalendarPage : ContentPage
{
    private ActivityIndicator activityIndicator = new ActivityIndicator() { IsRunning = false };
    private ObservableCollection<Calendar> calendars = new ObservableCollection<Calendar>();
    private string url = "[censored]";
    private int start = 0;
    private int limit = 10;

    public CalendarPage()
    {
        InitializeComponent();
        LoadCalendar();
    }

    private void RefreshCalendar(object sender, EventArgs e)
    {
        LoadCalendar();
        CalendarRefresh.IsRefreshing = false;
    }

    private void ScrollCalendar(object sender, ItemsViewScrolledEventArgs e)
    {
        if (e.LastVisibleItemIndex > (start - limit))
        {
            LoadCalendar();
        }
    }

    private async void LoadCalendar()
    {
        if (activityIndicator.IsRunning == true)
        {
            return;
        }
        else
        {
            activityIndicator.IsRunning = true;

            var http = new HttpClient();
            var items = await http.GetFromJsonAsync<List<Calendar>>(url + start + limit);

            foreach (var item in items)
            {
                calendars.Add(item);
            }

            CalendarView.ItemsSource = calendars;

            activityIndicator.IsRunning = false;

            start += limit;
        }
    }
}

日历类

项目是通过外部API收集的,因此有一个项目模板。

namespace projectName;

public class Calendar
{
    public int item_id { get; set; }
    public int status { get; set; }
    public Name name { get; set; }
}

public class Name
{
    public string common { get; set; }
    public string scientific { get; set; }
    public string color { get; set; }
}
inn6fuwd

inn6fuwd1#

您可以使用Binding value converters
您可以定义一个继承IValueConverter的ColorChangedConverter:

public class ColorChangedConverter : IValueConverter
{
    public ColorChangedConverter()
    {
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (...)
        {
            return Colors.Red;
        }
        else
        {
            return Colors.Blue;
        }                      
    }

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

在xaml中,consume Converters:

<ContentPage.Resources>
    <local:ColorChangedConverter x:Key="colorChangedConverter" />
</ContentPage.Resources>

...

<Label x:Name="LabelCommonName" BackgroundColor="{Binding name.color,Converter={StaticResource colorChangedConverter}}"
                                       Text="{Binding name.common}">

希望能成功。

相关问题