46

I have a number of elements in my XAML which define Foreground="#555" to be the color of faded text in a readonly textbox.

<TextBlock Text="{Binding SingularModelClassFileTitle}" Margin="0 10 0 0"/>
<TextBox Text="{Binding SingularModelClassFileName}"
         HorizontalAlignment="Left"
         IsReadOnly="True"
         Foreground="#555"
         Width="500"/>
<TextBox 
 VerticalScrollBarVisibility="Visible"
 AcceptsReturn="True"                  
 Width="500" 
 Height="100" 
 IsReadOnly="True" 
 Foreground="#555"
 Text="{Binding SingularModelClassContent}"
 HorizontalAlignment="Left"
 Margin="0 0 0 20"/>

How can I put this value in a XAML variable and reference in each attribute it so that I only have to change it in one place?

I'm thinking you can do something like this:

<sys:String x:Key="ReadOnlyTextColor">#555</sys:String>

...

    <TextBox Foreground="{StaticResource ReadOnlyTextColor}"/>

And what would be the property xmlns:sys=... reference for this?

1
  • 6
    You ask good questions, Edward. While learning WPF you name pops up time and again ;-) Commented Apr 4, 2011 at 21:09

2 Answers 2

65

Try defining your color as a SolidColorBrush:

<SolidColorBrush x:Key="ReadOnlyTextBrush" Color="#555555" />

...

<TextBox Foreground="{StaticResource ReadOnlyTextColor}" />
2
  • Matt, is the reason Color can't be used directly as a StaticResource because it's a value type, not a reference type?
    – Matt Davis
    Commented Jan 25, 2014 at 17:19
  • 1
    @MattDavis Color cannot be used because the Foreground property of TextBox is of type Brush. You can create a Color and reference that as StaticResource within the SolidColorBrush. Commented Aug 20, 2018 at 14:01
55

Sometimes you may need to define colors rather than brushes : (one case you would want this is to be able to define Gradients with color parameters) In that case you could just define them like this:

 <Color x:Key="ButtonColor1">Blue</Color>
 <Color x:Key="ButtonColor1">#AABBCC</Color>
 <Color x:Key="ButtonColor1" A="0" R="124" G="111" B="44"/>
4
  • 2
    Sadly, the last option throws "Failed to create a 'System.Byte' from the text '00'." on Windows Phone. The second one worked like a charm, cheers!
    – Agent_L
    Commented Aug 16, 2012 at 10:07
  • 1
    And then to reference the color use {StaticResource Blue} Commented Apr 20, 2014 at 9:28
  • 7
    @StephenHosking, no, to reference the color use {StaticResource ButtonColor1}
    – Rocklan
    Commented Jan 23, 2018 at 0:50
  • 1
    The last one should be A="0". You're working with bytes here, not string representations of hex digits. Commented Aug 20, 2018 at 14:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.