【发布时间】:2015-07-29 12:22:00
【问题描述】:
我需要做这样的事情Controlling the Length of a RichTextBox in C#
但在 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”类型的参数 (您是否缺少 using 指令或程序集引用?)
错误 2 方法 'Select' 没有重载需要 2 个参数
显然 Text 属性在 WPF 中不起作用,请参阅此页面 RichTextBox (WPF) does not have string property “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 中实现这一点。
提前致谢。
【问题讨论】:
-
我以前没用过WPF,但它是
Document属性吗? MSDN 将其描述为“获取或设置表示 RichTextBox 内容的 FlowDocument。” -
@Ric 我更新了我的问题,发现解决了属性 Text 的问题,但不适用于 Select 方法。
标签: c# wpf richtextbox