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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/979876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:45:18  来源:igfitidea点击:

Set background color of WPF Textbox in C# code

c#.netwpfbackground-color

提问by Sauron

How can I change the background and foreground colors of a WPF Textbox programmatically in C#?

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

采纳答案by Timbo

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:

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;

回答by James Hay

I take it you are creating the TextBox in XAML?

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

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:

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

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

回答by Daniel

Have you taken a look at Color.FromRgb?

你看了Color.FromRgb吗?

回答by Danield

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:

或者您可以在 XAML 中设置 SolidColorBrush 资源,然后在代码隐藏中使用 findResource:

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

回答by Mwaffak Jamal Zakariya

You can convert hex to RGB:

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

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

回答by Mwaffak Jamal Zakariya

You can use hex colors:

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

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