4

I'm working on a UWP app in windows 10 and I am trying to change the background color of a button in a click event. This is my code:

private void button1_1_Click(object sender, RoutedEventArgs e)
{
    if (_Sign)
    {
        button_1_1.Content = "Cross";
        _Sign = false;
    }
    else
    {
        // button_1_1.Background = new SolidColorBrush(new Windows.UI.Color )    

        // indows.UI.Colors clr = new Windows.UI.Colors(new SolidColorBrush red);

        // SolidColorBrush color = new SolidColorBrush();
        // color = new SolidColorBrush.
        // button_1_1.Background = clr;

        button_1_1.Content = "Tick";
        _Sign = true;
    }
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Ammar Shaukat
  • 345
  • 6
  • 17
  • 1
    You might have better luck doing it in XAML rather than code behind. [This thread](http://stackoverflow.com/questions/25414686/wpf-changing-button-background-on-click) might help. – Arian Motamedi Feb 17 '16 at 17:40
  • yes it's good but I need to change the color from C# code as I'm working on different scenario. – Ammar Shaukat Feb 17 '16 at 17:44

3 Answers3

6

Use the predefined color objects from the Colors properties:

button_1_1.Background = new SolidColorBrush(Windows.UI.Colors.White);
Denise Skidmore
  • 2,286
  • 22
  • 51
1

You can do just that

button1.SetValue(BackgroundProperty,new SolidColorBrush(Windows.UI.Colors.Black));

You can play with that! I am not on my pc now to check it but something like that works.

or you can try

button1.Background = new SolidColorBrush(Windows.Ui.Colors.Black);
Giorgos Neokleous
  • 1,709
  • 1
  • 14
  • 25
  • 1
    "BackgroundPropert***y***" and "U***I***". Just mentioning so people can copy / paste without errors. – RareNCool Feb 17 '16 at 19:49
1

You can also provide different color

 SolidColorBrush mySolidColorBrush = new SolidColorBrush();
   mySolidColorBrush.Color = Color.FromArgb(0, 255, 244, 244);
 button1.Background = mySolidColorBrush;

U have to just convert a color code to Argb like this

return new SolidColorBrush(
                Color.FromArgb(
                    255,
                    Convert.ToByte(hexaColor.Substring(1, 2), 16),
                    Convert.ToByte(hexaColor.Substring(3, 2), 16),
                    Convert.ToByte(hexaColor.Substring(5, 2), 16)
                )
            );

its very easy and proper because you can give any color not a default color like black ,orange etc.

Hardik Kothari
  • 1,686
  • 1
  • 15
  • 29