繁体   English   中英

在wpf C#中控制RichTextBox的长度

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM