我有这个代码,在文本框中的文本下添加虚线:
// 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;
我的问题是我只需要格式化文本中的最后6个字符!
我知道如何实现这一目标?
答案 0 :(得分:1)
不是在整个TextBlock上设置属性,而是为最后六个字符创建一个TextRange并将格式应用于:
var end = PasswordSendMessage.ContentEnd;
var start = end.GetPositionAtOffset(-6) ?? PasswordSendMessage.ContentStart;
var range = new TextRange(start, end);
range.ApplyPropertyValue(Inline.TextDecorationsProperty, myCollection);
如果PasswordSendMessage是TextBox而不是TextBlock,则不能使用这样的富文本。您可以使用RichTextBox,在这种情况下,此技术可以使用,但您需要使用PasswordSendMessage.Document.ContentEnd
和PasswordSendMessage.Document.ContentStart
而不是PasswordSendMessage.ContentEnd
和PasswordSendMessage.ContentStart
。
答案 1 :(得分:0)
您可以将文本数据绑定到TextBox的Inlines属性,并创建一个转换器来构建运行集合,并为应用装饰的最后6个字符单独运行