public class Item{ public Color Color { get; set; } = Colors.Red;}public class ViewModel : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; public List<Item> List { get; set; } = new(); public ICommand ButtonPressedCommand { get; set; } public ViewModel() { List.Add(new Item()); List.Add(new Item()); List.Add(new Item()); ButtonPressedCommand = new Command<Item>(ButtonPressed); } public void ButtonPressed(Item item) { item.Color = Colors.Green; OnPropertyChanged(nameof(List)); } public void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }}
<?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:Test" x:Class="Test.MainPage" x:DataType="local:ViewModel"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="Center"> <CollectionView ItemsSource="{Binding List}"> <CollectionView.ItemTemplate> <DataTemplate> <Button x:DataType="local:Item" Text="Press me" BackgroundColor="{Binding Color}" CommandParameter="{Binding .}" Command="{Binding Source={RelativeSource AncestorType={x:Type local:ViewModel}}, Path=ButtonPressedCommand}"/> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </VerticalStackLayout> </ScrollView></ContentPage>