File size: 1,837 Bytes
f553413 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;
namespace WpfRichTextBox
{
public class CustomRichTextBox : RichTextBox
{
public List<RichChar> RichChars { get; private set; } = new List<RichChar>();
public CustomRichTextBox()
{
TextChanged += CustomRichTextBox_TextChanged;
}
private void CustomRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
SyncRichChars();
InvalidateVisual();
}
private void SyncRichChars()
{
RichChars.Clear();
var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
for (int i = 0; i < text.Length; i++)
{
RichChars.Add(new RichChar
{
Character = text[i],
Position = new Point(i * 16, 10), // 横向排列,纵坐标可调整
Color = Colors.Black // 默认颜色
});
}
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
foreach (var richChar in RichChars)
{
var formattedText = new FormattedText(
richChar.Character.ToString(),
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Segoe UI"),
16,
new SolidColorBrush(richChar.Color),
VisualTreeHelper.GetDpi(this).PixelsPerDip);
drawingContext.DrawText(formattedText, richChar.Position);
}
}
}
} |