fasdfsa commited on
Commit
79a2724
·
1 Parent(s): f553413

fix 粘贴溢出到窗体

Browse files
Files changed (1) hide show
  1. CustomRichTextBox.cs +25 -13
CustomRichTextBox.cs CHANGED
@@ -14,6 +14,13 @@ namespace WpfRichTextBox
14
  public CustomRichTextBox()
15
  {
16
  TextChanged += CustomRichTextBox_TextChanged;
 
 
 
 
 
 
 
17
  }
18
 
19
  private void CustomRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
@@ -26,13 +33,15 @@ namespace WpfRichTextBox
26
  {
27
  RichChars.Clear();
28
  var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
29
- for (int i = 0; i < text.Length; i++)
 
 
30
  {
31
  RichChars.Add(new RichChar
32
  {
33
  Character = text[i],
34
- Position = new Point(i * 16, 10), // 横向排列,纵坐标可调整
35
- Color = Colors.Black // 默认颜色
36
  });
37
  }
38
  }
@@ -42,16 +51,19 @@ namespace WpfRichTextBox
42
  base.OnRender(drawingContext);
43
  foreach (var richChar in RichChars)
44
  {
45
- var formattedText = new FormattedText(
46
- richChar.Character.ToString(),
47
- System.Globalization.CultureInfo.CurrentCulture,
48
- FlowDirection.LeftToRight,
49
- new Typeface("Segoe UI"),
50
- 16,
51
- new SolidColorBrush(richChar.Color),
52
- VisualTreeHelper.GetDpi(this).PixelsPerDip);
53
-
54
- drawingContext.DrawText(formattedText, richChar.Position);
 
 
 
55
  }
56
  }
57
  }
 
14
  public CustomRichTextBox()
15
  {
16
  TextChanged += CustomRichTextBox_TextChanged;
17
+ DataObject.AddPastingHandler(this, OnPasteHandler);
18
+ }
19
+
20
+ private void OnPasteHandler(object sender, DataObjectPastingEventArgs e)
21
+ {
22
+ SyncRichChars();
23
+ InvalidateVisual();
24
  }
25
 
26
  private void CustomRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
 
33
  {
34
  RichChars.Clear();
35
  var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
36
+ int maxChars = (int)(ActualWidth / 16);
37
+ int count = Math.Min(text.Length, maxChars);
38
+ for (int i = 0; i < count; i++)
39
  {
40
  RichChars.Add(new RichChar
41
  {
42
  Character = text[i],
43
+ Position = new Point(i * 16, 10),
44
+ Color = Colors.Black
45
  });
46
  }
47
  }
 
51
  base.OnRender(drawingContext);
52
  foreach (var richChar in RichChars)
53
  {
54
+ if (richChar.Position.X >= 0 && richChar.Position.X + 16 <= ActualWidth && richChar.Position.Y >= 0 && richChar.Position.Y + 16 <= ActualHeight)
55
+ {
56
+ var formattedText = new FormattedText(
57
+ richChar.Character.ToString(),
58
+ System.Globalization.CultureInfo.CurrentCulture,
59
+ FlowDirection.LeftToRight,
60
+ new Typeface("Segoe UI"),
61
+ 16,
62
+ new SolidColorBrush(richChar.Color),
63
+ VisualTreeHelper.GetDpi(this).PixelsPerDip);
64
+
65
+ drawingContext.DrawText(formattedText, richChar.Position);
66
+ }
67
  }
68
  }
69
  }