WpfRichTextBox / CustomRichTextBox.cs
fasdfsa's picture
init
f553413
raw
history blame
1.84 kB
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);
}
}
}
}