197

如何在 C# 中以编程方式更改 WPF 文本框的背景和前景色?

4

8 回答 8

364
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;

WPF Foreground and Background 是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;
于 2009-06-11T08:06:01.533 回答
111

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

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");
于 2011-11-07T08:09:05.770 回答
24

我认为您是在 XAML 中创建 TextBox 吗?

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

myTextBox.Background = new SolidColorBrush(Colors.White);
于 2009-06-11T08:06:13.750 回答
6

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

string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
于 2012-04-30T03:03:48.717 回答
5

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

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
于 2012-04-30T03:40:34.640 回答
2

你看过了Color.FromRgb吗?

于 2010-04-29T21:43:23.067 回答
2

我知道这已在另一篇 SOF 帖子中得到解答。但是,如果您知道十六进制,则可以执行此操作。

textBox1.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#082049");
于 2021-02-24T20:08:04.467 回答
0

BrushConverter bc = new BrushConverter();

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

buttonName.Foreground = new SolidColorBrush(Colors.Gray);

参考这里 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/

于 2021-08-26T02:44:14.210 回答