daniyalahmad
daniyalahmad

Reputation: 3863

C# Change color of one character in a text box

C# - WPF : how can I change the color of just one character in a text box ? example : Word Hello, Color of H becomes Red

Upvotes: 4

Views: 11252

Answers (2)

user1567896
user1567896

Reputation: 2398

You can not do this with a textbox, but you can use a richtextbox: WPF RichTextBox Tutorial

var textRange = MyRichTextBox.Selection;
var start = MyRichTextBox.Document.ContentStart;
var startPos = start.GetPositionAtOffset(0);
var endPos = start.GetPositionAtOffset(1);
textRange.Select(startPos, endPos);
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));

Upvotes: 6

mgokhanbakal
mgokhanbakal

Reputation: 1727

You can use richtexbox like below: You can even change backcolor for a particular character as well

richTextBox1.SelectionStart = characterStartIndex;
richTextBox1.SelectionLength = 1;
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectionBackColor = Color.Yellow;

Upvotes: 3

Related Questions