2

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.

2 Answers 2

4

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yeah. I thought specifying System.Drawing.Color and not System.Windows.Media.Color was enough. Anyways sorry for confusion. Upvoted your answer. Can't mark two answers as answered. You did answer it though.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.