在 WPF 中使用 System.Drawing.Color 设置背景和前景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21469281/
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-09-13 10:40:47  来源:igfitidea点击:

Use System.Drawing.Color to set background and foreground in WPF

c#.netwpfsilverlightxaml

提问by user2330678

How can I set background and foreground properties of WPF textblocks, using a System.Drawing.Color programmatically ? A solution without a converter would be nice.

如何使用 System.Drawing.Color 以编程方式设置 WPF 文本块的背景和前景属性?没有转换器的解决方案会很好。

System.Drawing.Color BackColor = System.Drawing.Color.Black;
System.Drawing.Color ForeColor = System.Drawing.Color.White;

TextBlock txt = new TextBlock ();
txt.Background=BackColor ;
txt.ForeGround=ForeColor ;

PS: The color I would be assigining would be from a windows forms app and hence it would be a System.Drawing.Color not a System.Windows.Media.Color as required by WPF.

PS:我要分配的颜色将来自 Windows 窗体应用程序,因此它将是 System.Drawing.Color 而不是 WPF 要求的 System.Windows.Media.Color。

采纳答案by Clemens

You might do it like this:

你可以这样做:

System.Drawing.Color BackColor = System.Drawing.Color.Black;

txt.Background = new SolidColorBrush(
    Color.FromArgb(BackColor.A, BackColor.R, BackColor.G, BackColor.B));

回答by ChrisF

You need to use a Brushrather than an Color.

您需要使用 aBrush而不是Color

There are several predefined brushes so you could do this:

有几个预定义的画笔,所以你可以这样做:

txt.Background = Brushes.Black;
txt.Foreground = Brushes.White;

MSDN Page

MSDN页面

However, as you are reading the colour from a Windows Form App then you'll have to create your Brushfrom the component colours:

但是,当您从 Windows 窗体应用程序读取颜色时,您必须Brush从组件颜色创建您的颜色:

txt.Background = new SolidColorBrush(Color.FromArgb(BackColor.A, BackColor.R, BackColor.G, BackColor.B));