public partial class ButtonColorCollectionView
{
public ButtonColorCollectionView() => InitializeComponent();
}
public partial class ButtonColorCollectionViewModel : ObservableObject
{
public ObservableCollection<ButtonItemViewModel> Buttons { get; } = [];
private readonly DispatcherTimer _timer;
public ButtonColorCollectionViewModel()
{
for (var i = 0; i < 12; i++) { Buttons.Add(new ButtonItemViewModel { ButtonText = $"{i}- Click Me", }); }
_timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1), };
_timer.Tick += Timer_Tick;
_timer.Start();
}
private void Timer_Tick(object? sender, EventArgs e)
{
var buttonsToPick = Random.Shared.Next(1, 4);
foreach (var button in Buttons.OrderBy(_ => Random.Shared.Next()).Take(buttonsToPick)) { button.ClickedButtonCommand.Execute(null); }
}
}
public partial class ButtonItemViewModel : ObservableObject
{
private static readonly SolidColorBrush GoodColor = Brushes.LimeGreen;
private static readonly SolidColorBrush BadColor = Brushes.Crimson;
[ObservableProperty] private SolidColorBrush _buttonBackground = Brushes.LightGray;
[ObservableProperty] private string _buttonText = "Click me!";
[RelayCommand] private void ClickedButton() => ButtonBackground = Random.Shared.NextDouble() < 0.5 ? GoodColor : BadColor;
}