How can I change the background and foreground colors of a WPF Textbox programmatically in C#?
8 Answers
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;
WPF Foreground and Background is of type System.Windows.Media.Brush
. You can set another color like this:
using System.Windows.Media;
textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;
-
2If we want to set a hex value to the color attribute , how it can be done??– SauronMar 4, 2010 at 11:40
-
11You could use something like Brush brush = new SolidColorBrush( Color.FromRgb( r, g, b ) );– TimboMar 4, 2010 at 13:17
-
3There is also the much prettier
LinearGradientBrush
:) Apr 29, 2010 at 21:45 -
7
If you want to set the background using a hex color you could do this:
var bc = new BrushConverter();
myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX");
Or you could set up a SolidColorBrush resource in XAML, and then use findResource in the code-behind:
<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX");
-
It is much preferable to use
(System.Windows.Media.Brush)Application.Current.FindResource("BrushFFXXXXX");
as your application will not throw a threading exception if it is upgraded to use multiple dispatcher threads in the future.– ContangoNov 8, 2016 at 14:46 -
Where should
<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
be declared? When I try do so inside<Window x:Class ...
I get error: "The property 'Content' is set more than once"– amyNov 11, 2020 at 17:03
I take it you are creating the TextBox in XAML?
In that case, you need to give the text box a name. Then in the code-behind you can then set the Background property using a variety of brushes. The simplest of which is the SolidColorBrush:
myTextBox.Background = new SolidColorBrush(Colors.White);
You can use hex colors:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
You can convert hex to RGB:
string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
-
System.Windows.Media.Color FromArgb is accepting byte a, byte r, byte g, byte b, not int– PawelJun 15, 2021 at 9:21
I know this has been answered in another SOF post. However, you could do this if you know the hexadecimal.
textBox1.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#082049");
BrushConverter bc = new BrushConverter();
textName.Background = (Brush)bc.ConvertFrom("#FF7BFF64");
buttonName.Foreground = new SolidColorBrush(Colors.Gray);