C# Change A Button's Background Color

2019-01-11 16:31发布

Using C# and Visual Studio 2010, how can I change the background color of a button once another button is pressed? Am I not including a System.? wrong?

What I have at the moment is:

ButtonToday.Background = Color.Red;

And it's not working.

6条回答
一纸荒年 Trace。
2楼-- · 2019-01-11 17:07

I doubt if any of those should work. Try: First import the namespace in the beginning of the code page as below.

using System.Drawing;

then in the code.

Button4.BackColor = Color.LawnGreen;

Hope it helps.

查看更多
做个烂人
3楼-- · 2019-01-11 17:14

I had trouble at first with setting the colors for a WPF applications controls. It appears it does not include System.Windows.Media by default but does include Windows.UI.Xaml.Media, which has some pre-filled colors.

I ended up using the following line of code to get it to work:

grid.Background.SetValue(SolidColorBrush.ColorProperty, Windows.UI.Colors.CadetBlue);

You should be able to change grid.Background to most other controls and then change CadetBlue to any of the other colors it provides.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-11 17:16
// WPF

// Defined Color
button1.Background = Brushes.Green;

// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
查看更多
乱世女痞
5楼-- · 2019-01-11 17:31

WinForm:

private void button1_Click(object sender, EventArgs e)
{
   button2.BackColor = Color.Red;
}

WPF:

private void button1_Click(object sender, RoutedEventArgs e)
{
   button2.Background = Brushes.Blue;
}
查看更多
贪生不怕死
6楼-- · 2019-01-11 17:31

In WPF, the background is not a Color, it is a Brush. So, try this for starters:

using System.Windows.Media;

// ....

ButtonToday.Background = new SolidColorBrush(Colors.Red);

More sensibly, though, you should probably look at doing this in your Xaml instead of in code.

查看更多
做自己的国王
7楼-- · 2019-01-11 17:31

Code for set background color, for SolidColor:

button.Background = new SolidColorBrush(Color.FromArgb(Avalue, rValue, gValue, bValue));
查看更多
登录 后发表回答