Derek Lakin

Changing the Caret Colour in WPF

In WPF, you don’t have direct control over the colour of the caret in a TextBox or a RichTextBox. What the framework does is to use the inverse of the colour that you choose for the Background property. I’ve seen a few examples of styles that explicitly set the Background property to {x:Null} to completely remove the background from the TextBox, which enables you to use the same style when then the TextBox is used on top of different backgrounds that you want to show through.

Because the framework uses the inverse of the Background colour to set the colour of the caret, if you set the Background property to {x:Null}, then you will end up with the default black caret, which on a black background can be particularly difficult to see!

The Solution

The simple solution to this problem is to use actually specify a value for the Background property. In the case where you have a black background and want a white caret, then you can set the value of the Background property to #00000000, which is completely transparent black (if that makes sense!). The framework appears to ignore the opacity component of the colour so you end up with a transparent background and a white caret!

Taking it One Step Further

I haven’t tried this yet, but I assume that you can take this approach one step further to customise the colour of your caret by setting the Background to different colours with an opacity value of zero. This would then be a simpler solution that completely overriding the style as described by Lester in his Changing caret color in (Rich)TextBox post.

This work is licensed under a [Creative Commons Attribution By license.](