[英]Controlling the Length of a RichTextBox in wpf C#
我需要做這樣的事情在C#中控制RichTextBox的長度
但是在WPF中:
if (richTextBox.Text.Length > maxsize)
{
// this method preserves the text colouring
// find the first end-of-line past the endmarker
Int32 endmarker = richTextBox.Text.IndexOf('\n', dropsize) + 1;
if (endmarker < dropsize)
endmarker = dropsize;
richTextBox.Select(0, endmarker);
richTextBox.Cut();
}
這會引發編譯錯誤
錯誤1'System.Windows.Controls.RichTextBox'不包含'Text'的定義,並且找不到擴展方法'Text'接受類型為'System.Windows.Controls.RichTextBox'的第一個參數(您是否缺少使用指令還是程序集引用?)
錯誤2方法'選擇'沒有重載需要2個參數
顯然,Text屬性在WPF中不起作用,請參閱此頁面RichTextBox(WPF)沒有字符串屬性“ Text” ,這個問題我為Text屬性找到了解決方案,但Select方法卻沒有。
var myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
if (myText.Text.Length > maxsize)
{
// this method preserves the text colouring
// find the first end-of-line past the endmarker
Int32 endmarker = myText.Text.IndexOf('\n', dropsize) + 1;
if (endmarker < dropsize)
endmarker = dropsize;
richTextBox.Select(0, endmarker);//No overload for method 'Select' takes 2 arguments
myText.Select(0, endmarker);//No overload for method 'Select' takes 2 arguments
console.Cut();
}
所以現在,我如何在WPF中實現這一目標。
提前致謝。
RichTextBox沒有Text屬性,您現在正在做的事情就是將其移動,可以通過將其移至全局擴展方法來改進代碼:
public static class Extentions
{
public static string Text(this RichTextBox richTextBox)
{
TextRange content = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
return content.Text;
}
}
編輯:
如果您的最終目標是從控件中選擇一些文本,則根本不需要Text屬性:
對於RichTextBox Selection,您必須使用TextPointer:
TextPointer text = richTextBox.Document.ContentStart;
while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
text = text.GetNextContextPosition(LogicalDirection.Forward);
}
TextPointer startPos = text.GetPositionAtOffset(0);
TextPointer endPos = text.GetPositionAtOffset(endmarker);
var textRange = new TextRange(startPos, endPos);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Blue));
編輯2:將文本追加到RichTextEditors。
private void processLine(string line)
{
//You can clear if necessary
//richTextBox.Document.Blocks.Clear();
//whatever your logic. I'm only taking the first 10 chars
string trimmed = text.Substring(0,9);
richTextBox.Document.Blocks.Add(new Paragraph(new Run(trimmed)));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.