File size: 2,868 Bytes
f553413 8c0ac5d f553413 a2132ef e202030 f553413 8c0ac5d f553413 a2132ef 8c0ac5d 79a2724 e202030 79a2724 f553413 8c0ac5d f553413 e202030 f553413 e202030 f553413 e202030 f553413 e202030 f553413 e202030 f553413 e202030 f553413 e202030 f553413 e202030 79a2724 e202030 79a2724 e202030 79a2724 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;
namespace WpfRichTextBox
{
public class Editor : RichTextBox
{
public int _fontsize = 16;
public List<TextLine> TextLines { get; private set; } = new List<TextLine>();
public Editor()
{
FontManager.SetProgrammingFont(this, _fontsize);
TextChanged += Editor_TextChanged;
DataObject.AddPastingHandler(this, OnPasteHandler);
}
private void OnPasteHandler(object sender, DataObjectPastingEventArgs e)
{
SyncTextLines();
InvalidateVisual();
}
private void Editor_TextChanged(object sender, TextChangedEventArgs e)
{
SyncTextLines();
InvalidateVisual();
}
private void SyncTextLines()
{
TextLines.Clear();
var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
var lines = text.Split('\n');
for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
{
var line = lines[lineIndex];
var textLine = new TextLine();
for (int i = 0; i < line.Length; i++)
{
textLine.RichChars.Add(new RichChar
{
Character = line[i],
Position = new Point(i * _fontsize, lineIndex * _fontsize),
Color = Colors.Black
});
}
TextLines.Add(textLine);
}
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
foreach (var textLine in TextLines)
{
foreach (var richChar in textLine.RichChars)
{
if (richChar.Position.X >= 0 && richChar.Position.X + _fontsize <= ActualWidth && richChar.Position.Y >= 0 && richChar.Position.Y + _fontsize <= ActualHeight)
{
var formattedText = new FormattedText(
richChar.Character.ToString(),
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch),
_fontsize,
new SolidColorBrush(richChar.Color),
VisualTreeHelper.GetDpi(this).PixelsPerDip);
drawingContext.DrawText(formattedText, richChar.Position);
}
}
}
}
}
} |