在c#代码中设置WPF文本框的背景颜色

我如何能改变一个WPF文本框的背景和前景的颜色在c#编程?

464794 次浏览
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;

WPF前台和后台的类型是System.Windows.Media.Brush。你可以像这样设置另一种颜色:

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;

我认为你是在XAML中创建的文本框?

在这种情况下,您需要给文本框一个名称。然后在后台代码中,您可以使用各种画笔设置Background属性。其中最简单的是SolidColorBrush:

myTextBox.Background = new SolidColorBrush(Colors.White);

你看过Color.FromRgb吗?

如果你想使用十六进制颜色设置背景,你可以这样做:

var bc = new BrushConverter();


myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX");

或者你可以在XAML中设置一个SolidColorBrush资源,然后在后台代码中使用findResource:

<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX");

你可以将十六进制转换为RGB:

string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

你可以使用十六进制颜色:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

我知道这个问题已经在另一个特种部队的帖子中得到了回答。然而,如果你知道十六进制,你也可以这么做。

textBox1.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#082049");

BrushConverter bc = new BrushConverter();

textName。Background = (Brush)bc.ConvertFrom("#FF7BFF64");

buttonName。前景=新SolidColorBrush(Colors.Gray);

< p >参考这里 https://www.it-mure.jp.net/ja/c%23/c%EF%BC%83%E3%82%B3%E3%83%BC%E3%83%89%E3%81%A7wpf%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%83%9C%E3%83%83%E3%82%AF%E3%82%B9%E3%81%AE%E8%83%8C%E6%99%AF%E8%89%B2%E3%82%92%E8%A8%AD%E5%AE%9A%E3%81%99%E3%82%8B/957683208/ < / p >