user2330678
user2330678

Reputation: 2311

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

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 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.

Upvotes: 2

Views: 8337

Answers (2)

ChrisF
ChrisF

Reputation: 137188

You need to use a Brush rather than an Color.

There are several predefined brushes so you could do this:

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

MSDN Page

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

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

Upvotes: 4

Clemens
Clemens

Reputation: 128136

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));

Upvotes: 1

Related Questions