Click here to Skip to main content
16,020,261 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to change button's color when it is clicked. But it is not changing color. Here is my code.

What I have tried:

C#
 private SolidColorBrush[] _btnBrush;
        public SolidColorBrush[] btnBrush
        {
            get
            {
                return _btnBrush;
            }
            set
            {
                _btnBrush = value; OnPropertyChanged("btnBrush");
            }
        }

     public MineViewModel()
        {
         for (int i = 0; i < 100; i++)
             btnBrush[i] = (SolidColorBrush)new BrushConverter().ConvertFrom("#EED6C4");
}

Here is the method which the button is bind to:

C#
public void LeftClick(string id_no)
        {
          btnBrush[Convert.ToInt32(id_no)] = (SolidColorBrush)new BrushConverter().ConvertFrom("#B3541E");
}

and for XAML:

XML
<Button x:Name="btn4" Background="{Binding btnBrush[3]}" Command="{Binding LeftClickCommand}" CommandParameter="3"/>

This is executing correctly and the array is also getting the color. But it won't show on the UI.

If I bind it with a single solid brush, it works. But not with array of brushes. Any help?
Posted
Updated 3-Feb-22 7:07am
v2

1 solution

You are changing an element within an array. That will not raise any "property changed" events, so the UI has no idea that the binding needs to be updated.

Try replacing your array with an ObservableCollection<>:
C#
public ObservableCollection<SolidColorBrush> btnBrush { get; } = CreateBrushes();

private static ObservableCollection<SolidColorBrush> CreateBrushes()
{
    Color color = Color.FromRgb(0xEE, 0xD6, 0xC4);
    SolidColorBrush brush = new SolidColorBrush(color);
    IEnumerable<SolidColorBrush> brushes = Enumerable.Repeat(brush, 100);
    return new ObservableCollection<SolidColorBrush>(brushes);
}

public void LeftClick(int id_no)
{
    btnBrush[id_no] = new SolidColorBrush(Color.FromRgb(0xB3, 0x54, 0x1E));
}
ObservableCollection<T> Class (System.Collections.ObjectModel) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900