tags:

views:

32

answers:

2

Hi,

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?

A: 

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

MrDosu
`TextBlock.Inlines` is not a dependency property, so unfortunately you cannot bind to it using data binding.
Quartermeister
Ohh, should have looked that up. One can always go the attached prop route in such cases.
MrDosu
+1  A: 

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.

Quartermeister