Shawn Wildermuth

Author, Teacher, and Filmmaker
.NET Foundation Board Member

Silverlight 3 Hidden Features: TextBox.CaretBrush


Url: http://wilderminds.blob.core.windows.net/downloads/caretbrush.zip

Silverlight Logo

There has been a lot of interest in Silverlight 3 and all the new features. Lots of bloggers are hitting the big and bright features, but I am hoping to shine the light on some of the new stuff that's getting missed. Today its the TextBox.CaretBrush.

If you were going to theme your application (or just use dark colors) in Silverlight 2, there was a small problem: you couldn't change the color of the caret (the little line that shows you where you are typing).  This means that your TextBox's could look like this:

No CaretBrush

The caret is black so as long as your background is black, it didn't show up. In Silverlight 3 they are exposing this on the TextBox (and by derivation, the PasswordBox too). By setting the CaretBrush, you can specify how to paint the caret:

Caret Brush

You specify it like a simple property:

<TextBox Height="25"
         Width="100"
         Foreground="White"
         Background="Black"
         CaretBrush="White" />

You can also specify a more complex brush like a LinearGradient:

Linear Brush Caret

Like so:

<TextBox Height="25"
         Width="100"
         Foreground="White"
         Background="Black">
  <TextBox.CaretBrush>
    <LinearGradientBrush StartPoint="0,0"
                         EndPoint="0,1">
      <GradientStop Color="Orange"
                    Offset="0" />
      <GradientStop Color="Pink"
                    Offset=".5" />
      <GradientStop Color="Orange"
                    Offset="1" />
    </LinearGradientBrush>
  </TextBox.CaretBrush>
</TextBox>

 

In Silverlight 2 (and of course, still in Silverlight 3) you could always paint the selection.  For example, when the user selects some text, you can decide what brushes to use for foreground and background:

Foreground and Background Selection

This is done by specifying the SelectionForeground and SelectionBackground (and no, I don't know why they aren't called Brushes like the caret, probably backward compat with WPF):

<TextBox Height="25"
         Width="100"
         Foreground="White"
         Background="Black"
         CaretBrush="White"
         SelectionBackground="White"
        SelectionForeground="Black" />

Does this solve any Silverlight 2 problems you encountered?