我如何在C#中以编程方式更改WPF Textbox的背景和前景颜色?
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;
如果你想使用十六进制颜色设置背景,可以这样做:
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");
(System.Windows.Media.Brush)Application.Current.FindResource("BrushFFXXXXX");
,因为如果将来升级为使用多个调度程序线程,您的应用程序不会抛出线程异常。 - Contango<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
应该在哪里声明?当我尝试在 <Window x:Class ...
中这样做时,会出现错误:“属性 'Content' 被设置了多次”。 - amy我理解你正在使用XAML创建文本框?
在这种情况下,您需要给文本框命名。然后在代码后台中,您可以使用各种画笔设置背景属性。其中最简单的是SolidColorBrush:
myTextBox.Background = new SolidColorBrush(Colors.White);
string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
我知道这个问题在其他的SOF帖子中已经得到了解答。但是,如果你知道十六进制,你可以做到这一点。
textBox1.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#082049");
你有没有看过 Color.FromRgb
?
BrushConverter bc = new BrushConverter();
textName.Background = (Brush)bc.ConvertFrom("#FF7BFF64");
buttonName.Foreground = new SolidColorBrush(Colors.Gray);
刷子转换器 bc = new BrushConverter();
textName.Background = (Brush)bc.ConvertFrom("#FF7BFF64");
buttonName.Foreground = new SolidColorBrush(Colors.Gray);
LinearGradientBrush
:) - BlueRaja - Danny Pflughoeft