Click here to Skip to main content
14,738,282 members
Articles » Platforms, Frameworks & Libraries » Windows Presentation Foundation » Controls
Posted 19 Aug 2013

Tagged as


33 bookmarked

Customizing the Caret of a WPF TextBox

Rate me:
Please Sign up or sign in to vote.
4.86/5 (24 votes)
26 Dec 2013CPOL
How to create a custom caret for a WPF TextBox


This article describes the different ways a WPF TextBox Caret can be customized. It provides information on how to change the color, as well as a technique that will allow you to create your own custom Caret - providing you freedom with shape and size. 


What is a Caret? 

A Caret is the vertical 'blinking' line that represents the current cursor position of a control that accepts text input.  


By default, the Window's Caret is only 1-pixel wide and the shape is currently not modifiable using .NET. Even-though the thickness can be changed through the Windows Accessibility settings, it is an OS wide change, and not always desired if you want it to be application dependent. 

Changing the Caret color  

Starting in .NET 4.0, Microsoft has provided the capability to customize the Caret's color by providing the CaretBrush property of a TextBox control. The CaretBrush allows for easy color customization.

Using a style, the CaretBrush property can be set to specify the color (in this case blue). 

        <Style TargetType="{x:Type TextBox}" x:Key="TextBoxWithColoredCaretStyle">
            <Setter Property="CaretBrush">
                    <SolidColorBrush Color="Blue"/>
    <TextBox Height="47" FontSize="30" Name="textBox1" Width="289" Text="Code Project" 

         Style="{StaticResource TextBoxWithColoredCaretStyle}"/>

It can also be set simply through the TextBox property itself.

    <TextBox Height="47" FontSize="30" Name="textBox1" Width="289" Text="Code Project" 

             Style="{StaticResource TextBoxWithColoredCaretStyle}" CaretBrush="Blue"/>


The CaretBrush property can be used with a gradient brush as well.

    <TextBox Height="47" FontSize="30" Name="textBox1" Width="289" Text="Code Project">
            <LinearGradientBrush MappingMode="RelativeToBoundingBox"


                    <GradientStop Color="Blue"    Offset="0" />
                    <GradientStop Color="Magenta" Offset="0.5" />
                    <GradientStop Color="Green"   Offset="1" />



Creating your own Custom Caret 

In order to create our own custom Caret, we'll need to know two main things; the current position of the TextBox's built in Caret, and when the custom Caret needs to be moved/updated. Luckily, this information is available using the built in properties and events of the WPF TextBox

First, lets take a look at the XAML. 

<UserControl x:Class="CustomCaret.CustomCaretTextBox"






             d:DesignHeight="300" d:DesignWidth="300">
        <TextBox x:Name="CustomTextBox" 







            <Border x:Name="Caret" 






                    <EventTrigger RoutedEvent="Border.Loaded">
                            <Storyboard  x:Name="CaretStoryBoard" 




                                    <ColorAnimationUsingKeyFrames.KeyFrames >
                                        <DiscreteColorKeyFrame KeyTime="0:0:0.750" 

                        Value="Transparent" />
                                        <DiscreteColorKeyFrame KeyTime="0:0:0.000" 


As you can see, I've added the following 4 controls to a UserControl.    

  • Grid - This is the parent "container" of the TextBox and the other controls. A Grid is used so that the TextBox, Canvas, and Border overlap seamlessly. This is important because we want our custom Caret to appear as if it was part of the actual TextBox.  
  • TextBox - The TextBox where the 'built-in' Caret lives. We'll be referencing this TextBox to get notified when the 'built-in' Caret moves so that the position of our custom Caret can move as well. The TextBox will also provide us with the 'built-in' Caret's position. Notice the 'CaretBrush' of the TextBox is set to Transparent. This is required so that the 'built-in' Caret is not displayed and distracting the user from the custom Caret
  • Canvas - The Canvas is the area that the custom Caret will move on. Since it lives inside a Grid that is overlapping the actual TextBox, the custom Caret will appear as if it was part of the TextBox itself. 
  • Border - The Border is the actual custom Caret. This is what will be moving/updating across the Canvas. I've also added a Storyboard to the Border to simulate the blinking effect of a 'built-in' Caret. Even though this can be achieved in various ways, I felt a Storyboard was a bit easier as it can be implemented in pure XAML.  

Now, lets look at the code behind, 

/// <summary>
/// Initializes a new instance of the <see cref="CustomCaretTextBox"/> class.
/// </summary>
public CustomCaretTextBox()
    this.CustomTextBox.SelectionChanged += (sender, e) => MoveCustomCaret();
    this.CustomTextBox.LostFocus += (sender, e) => Caret.Visibility = Visibility.Collapsed;
    this.CustomTextBox.GotFocus += (sender, e) => Caret.Visibility = Visibility.Visible;

Inside the UserControl's constructor, I subscribe to three TextBox events (SelectionChanged, LostFocus, and GotFous).

The SelectionChanged event is important as it is responsible for notification of when the CaretIndex has changed. For example, when the user types, selects text, or uses the left and right arrow keys, the SelectionChanged event will get fired. Because of this, we'll also be notified of when the 'built-in' Caret has moved, which indicates that our custom Caret should be moved as well.

The next two events (LostFocus and GotFocus) are used simply for visual purposes of our custom Caret. We want to 'hide' the custom Caret when the TextBox is not focused and only show it when it is.

Lastly, the MoveCustomCaret method.  

/// <summary>
/// Moves the custom caret on the canvas.
/// </summary>
private void MoveCustomCaret()
    var caretLocation = CustomTextBox.GetRectFromCharacterIndex(CustomTextBox.CaretIndex).Location;
    if (!double.IsInfinity(caretLocation.X))
        Canvas.SetLeft(Caret, caretLocation.X);
    if (!double.IsInfinity(caretLocation.Y))
        Canvas.SetTop(Caret, caretLocation.Y);

This method is hooked up to the SelectionChanged TextBox event and is responsible for moving the custom Caret (the Border control) to a Point on the canvas. The Point is obtained using the Location of the 'built-in' Caret. By using GetRectFromCharacterIndex, we can get the Rectangle of the leading edge for the character that's at the index of the 'built-in' Caret. Calling Location on the Rectangle, we get the x and y-coordinates which are then used to move the custom Caret to that location on the canvas.  


The Caret can also be made using an image by simply replacing the Border control with an Image control. 

    <TextBox x:Name="CustomTextBox" 







        <Image x:Name="Caret" 





            Canvas.Top="0" Source="/CustomCaret;component/Carrot.png"/>




  • 2013, August 18  - Initial publication.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
Software Engineer - San Diego, CA

Comments and Discussions

BugDoubleclick Word Selection Pin
garzooma19-Sep-19 10:26
Membergarzooma19-Sep-19 10:26 
GeneralRe: Doubleclick Word Selection Pin
garzooma23-Sep-19 7:49
Membergarzooma23-Sep-19 7:49 
QuestionFlowDirection Pin
M.H. Shojaei13-Mar-19 20:07
MemberM.H. Shojaei13-Mar-19 20:07 
QuestionTextWrapping = "Wrap" causes issues Pin
VishalDPrajapati30-Oct-18 3:01
MemberVishalDPrajapati30-Oct-18 3:01 
QuestionTextWrapping="NoWrap" Pin 0:51 0:51 
QuestionCool Pin
Marco Bertschi7-Apr-16 3:26
professionalMarco Bertschi7-Apr-16 3:26 
AnswerRe: Cool Pin
d.moncada8-Apr-16 6:08
Memberd.moncada8-Apr-16 6:08 
GeneralMy vote of 5 Pin
fredatcodeproject26-Dec-13 14:00
professionalfredatcodeproject26-Dec-13 14:00 
GeneralRe: My vote of 5 Pin
d.moncada26-Dec-13 14:04
Memberd.moncada26-Dec-13 14:04 
GeneralCool Pin
Herbert Lausmann26-Dec-13 10:57
professionalHerbert Lausmann26-Dec-13 10:57 
Simple and pretty cool. Congratulations.
GeneralRe: Cool Pin
d.moncada5-Jan-14 10:05
Memberd.moncada5-Jan-14 10:05 
GeneralMy vote of 5 Pin
Jerameel11-Sep-13 23:06
MemberJerameel11-Sep-13 23:06 
GeneralRe: My vote of 5 Pin
d.moncada11-Sep-13 23:11
Memberd.moncada11-Sep-13 23:11 
GeneralMy vote of 5 Pin
fredatcodeproject19-Aug-13 11:44
professionalfredatcodeproject19-Aug-13 11:44 
GeneralRe: My vote of 5 Pin
d.moncada19-Aug-13 18:11
Memberd.moncada19-Aug-13 18:11 
GeneralMy vote of 4 Pin
fredatcodeproject19-Aug-13 4:51
professionalfredatcodeproject19-Aug-13 4:51 
GeneralRe: My vote of 4 Pin
d.moncada19-Aug-13 5:17
Memberd.moncada19-Aug-13 5:17 
GeneralRe: My vote of 4 Pin
fredatcodeproject19-Aug-13 6:40
professionalfredatcodeproject19-Aug-13 6:40 
GeneralRe: My vote of 4 Pin
d.moncada19-Aug-13 6:48
Memberd.moncada19-Aug-13 6:48 
GeneralRe: My vote of 4 Pin
d.moncada19-Aug-13 8:27
Memberd.moncada19-Aug-13 8:27 
GeneralRe: My vote of 4 Pin
fredatcodeproject19-Aug-13 11:44
professionalfredatcodeproject19-Aug-13 11:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.