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