|
|
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); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
} |