In the last article we demonstrated how to create a character counter for the RichTextBox control by making a custom SharpRichTextBox control. In this article we will demonstrate how to display the live character count as the background of the SharpRichTextBox control.

Why Show Count as the Background?

If your WPF application is limited in terms of space and you do not want to add an additional field to display the counter then showing the count in the background makes sense. It also helps the user to focus on the RichTextBox alone and not to glance at the other control which serves as the counter.

The Implementation:

The first thing to realize is that the Background of a WPF control is a brush. This means we can apply different kind of brushes to the background. In our implementation we used the VisualBrush. One of the great things about VisualBrush is that it will automatically adjust to fit the size of the container.



The SetUpBindingForBackground method is responsible for setting up the VisualBrush to the RichTextBox background. The textBlock instance is used to display the remaining characters and is defined as follows:



One important thing to note about the textBlock element is the opacity property. You do not want to place a dark bold text in the background of the RichTextBox as users will not be able to see what they are typing. This is why the opacity is set to 0.2. You can even go further down just make sure that the live counter is visible without much effort.

Next, we setup the style and binding and then add the textBlock instance to a StackPanel element. Finally, the visualBrush visual is set and the Background is set to the new visual brush.

Take a look at the animation below to see the code in action:



Conclusion:

In this article we demonstrated how to set the live character counter for our SharpRichTextBox custom control as the background.

[Download Sample]