简体   繁体   中英

Change the Background Color of an ListView Item on Xamarin Forms

I have a ListView that binds its items from an ObservableCollection , and a Button that changes an "Amount" property of a specific object of that ObservableCollection . And I want to change the BackgroundColor of these Items whose "Amount" has already been changed.

I've searched for a solution for that, but I couldn't find any.
Does anybody know a way for solving that?

One way to do it would be to add a new property, something like HasAmountChanged, bind the background color of the viewcell to that property, and use a ValueConverter to set the color. This would look something like the following:

The object class with the properties:

public class MyObject : INotifyPropertyChanged
{
    double amount;
    bool hasAmountChanged = false;

    public event PropertyChangedEventHandler PropertyChanged;

    public MyObject(double amount)
    {
        this.amount = amount;
    }

    public double Amount
    {
        get => amount;
        set
        {
            if (amount != value)
            {
                amount = value;
                OnPropertyChanged(nameof(Amount));
                HasAmountChanged = true;
            }
        }
    }

    public bool HasAmountChanged
    {
        get => hasAmountChanged;
        set
        {
            if (hasAmountChanged != value)
            {
                hasAmountChanged = value;
                OnPropertyChanged(nameof(HasAmountChanged));
            }
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The view. Notice the stacklayout inside the ViewCell, that's where the background color is set:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:Delete"
         x:Class="Delete.MainPage">

<ContentPage.Resources>
    <ResourceDictionary>
        <local:ListViewBackgroundColorConverter x:Key="ListViewColorConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

<StackLayout>
    <Button Text="Click Me" Clicked="ButtonClicked" />

    <ListView ItemsSource="{Binding MyItemsSource}" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Spacing="15" 
                                 BackgroundColor="{Binding HasAmountChanged, Converter={StaticResource ListViewColorConverter}}" 
                                 HorizontalOptions="FillAndExpand" 
                                 VerticalOptions="FillAndExpand">
                        <Label Text="FOO 1"/>
                        <Label Text="{Binding Amount}"/>
                        <Label Text="{Binding HasAmountChanged}" />
                        <Label Text="FOO 4"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</StackLayout>

The code behind of the view, included for completeness:

public partial class MainPage : ContentPage
{
    public ObservableCollection<MyObject> MyItemsSource { get; set; }

    public MainPage()
    {
        InitializeComponent();

        MyItemsSource = new ObservableCollection<MyObject>
        {
            new MyObject(1.14),
            new MyObject(1.14),
            new MyObject(1.14),
            new MyObject(1.14),
            new MyObject(1.14),
        };

        BindingContext = this;
    }

    void ButtonClicked(object sender, EventArgs e)
    {
        var rnd = new Random();

        var myObject = MyItemsSource[rnd.Next(0, MyItemsSource.Count)];

        myObject.Amount = 5.09;
    }
}

And finally the most important part, the converter:

public class ListViewBackgroundColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? Color.LawnGreen : Color.DarkRed;
    }

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

Note that you would actually want to check it's a bool coming in and handle that as well.

You could implement an array of booleans and change them to true when Amount gets changed. Then you might want to create a custom renderer for the color of each ListView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM