How can I change the background and foreground colors of a WPF Textbox programmatically in C#?
192
votes
7 Answers
357
votes
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;
110
votes
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");
24
votes
6
votes
5
votes