Using Hexadecimal Color Values in WPF 3.5

I am currently preparing for my WPF content for the Philippine Launch Wave of Visual Studio 2008, Windows Server 2008, and SQL Server 2008. As a seasoned web developer, I am quite accustomed to the colors that I frequently use in hexadecimal and I intend to use these colors in my demo. I have a basic XAML file that has a Window with a ListBox, TextBlock and Slider in it. I am trying to show how LINQ works in a WPF 3.5 application.

<window x:Class="WpfApplication1.Window1"
    Title="Window1" Height="500" Width="500">
        <listBox Name="listBox1" SelectionChanged="listBox1_SelectionChanged" Margin="0,0,0,120" />
        <textBlock Height="105" Name="textBlock1"  FontSize="{Binding ElementName=slider1, Path=Value}" VerticalAlignment="Bottom">Label</textBlock>
        <slider Height="21" Margin="203,0,-5,0" SizeChanged="slider1_SizeChanged" ValueChanged="slider1_ValueChanged" Minimum="10" Maximum="50" Name="slider1" VerticalAlignment="Bottom" Value="10" />

While working on a certain functionality that I want to display, I became curious if I can use the colors in my sample application. The color, which I don’t exactly know the name but I refer to it as maroonish red (the UP blood in me), has an hexadecimal value of “#cd0001”. I tried appending that value in the Foreground property of the TextBlock (textBlock1 mentioned above) but it doesn’t work.

// This code won't work

textBlock1.Foreground = "#cd0001";

// Even this

textBlock1.Foreground = (Brush)"#cd0001";

To have a workaround on this, you need to use the BrushConverter class in able to use your hexadecimal based colors as a brush.

BrushConverter bc = new BrushConverter();
Brush brush;
brush = (Brush)bc.ConvertFrom("#cd0001");
textBlock1.Foreground = brush;

And it works! If you are more familiar with the colors that you want in hexadecimal, you can replace the hex value in the text above and most likely that would work.



0 Responses to “Using Hexadecimal Color Values in WPF 3.5”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog Stats

  • 3,922 hits
March 2008
« Feb   Apr »

%d bloggers like this: