Mark
Mark

Reputation: 11

How to format specific text in WPF?

I have this code that adds dotted lines under text in text box:

      // Create an underline text decoration. Default is underline.
  TextDecoration myUnderline = new TextDecoration();

  // Create a linear gradient pen for the text decoration.
  Pen myPen = new Pen();
  myPen.Brush = new LinearGradientBrush(Colors.White, Colors.White, new Point(0, 0.5), new Point(1, 0.5));
  myPen.Brush.Opacity = 0.5;
  myPen.Thickness = 1.0;
  myPen.DashStyle = DashStyles.Dash;
  myUnderline.Pen = myPen;
  myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;

  // Set the underline decoration to a TextDecorationCollection and add it to the text block.
  TextDecorationCollection myCollection = new TextDecorationCollection();
  myCollection.Add(myUnderline);
  PasswordSendMessage.TextDecorations = myCollection;

My problem is I need only the last 6 characters in the text to be formatted!

Any idea how can I achieve that?

Upvotes: 1

Views: 504

Answers (2)

Quartermeister
Quartermeister

Reputation: 59139

Instead of setting the property on the entire TextBlock, create a TextRange for the last six characters and apply the formatting to that:

var end = PasswordSendMessage.ContentEnd;
var start = end.GetPositionAtOffset(-6) ?? PasswordSendMessage.ContentStart;
var range = new TextRange(start, end);
range.ApplyPropertyValue(Inline.TextDecorationsProperty, myCollection);

If PasswordSendMessage is a TextBox rather than a TextBlock, then you cannot use rich text like this. You can use a RichTextBox, in which case this technique will work but you will need to use PasswordSendMessage.Document.ContentEnd and PasswordSendMessage.Document.ContentStart instead of PasswordSendMessage.ContentEnd and PasswordSendMessage.ContentStart.

Upvotes: 1

MrDosu
MrDosu

Reputation: 3435

You could databind your text to the Inlines property of TextBox and make a converter to build the run collection with a seperate Run for the last 6 characters applying your decorations

Upvotes: 0

Related Questions