为什么';RichTextBox上的MaxLength属性是否在WPF中工作?
我试图在为什么';RichTextBox上的MaxLength属性是否在WPF中工作?,wpf,properties,Wpf,Properties,我试图在RichTextBox上设置MaxLength属性,但它似乎不起作用 有什么想法吗?在yout KeyDown事件中添加此代码 private void rLetter_KeyDown(object sender, KeyEventArgs e) { TextRange tr= new TextRange(rLetter.Document.ContentStart, rLet
RichTextBox
上设置MaxLength
属性,但它似乎不起作用
有什么想法吗?在yout KeyDown事件中添加此代码
private void rLetter_KeyDown(object sender, KeyEventArgs e)
{
TextRange tr= new TextRange(rLetter.Document.ContentStart, rLetter.Document.ContentEnd);
if (tr.Text.Length > 4000 || e.Key == Key.Space || e.Key == Key.Enter)
{
e.Handled = true;
return;
}
}
我有一些问题,错误是:
使用复制和粘贴文本max 4000测试此代码
对不起,我的英语…根本问题是WPF RichTextBox没有MaxLength属性-与Windows.Forms属性不同 这是@jhony的anwser的一个改进。如果捕获PreviewKeyDown事件并检查长度,还需要允许用户在达到限制后按Delete键和BackSpace键
// In constructor
this.RichTextBox.PreviewKeyDown += this.EditBox_KeyDown;
private void EditBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Delete && e.Key != Key.Back)
{
var range = new TextRange(this.RichTextBox.Document.ContentStart, this.RichTextBox.Document.ContentEnd);
if (range.Text.Length > this.MaxLength)
{
e.Handled = true;
return;
}
}
}
您还应该允许使用箭头键,因为您不希望它们被禁用
要禁用粘贴,请将其放入构造函数DataObject.AddPastingHandler(this.RichTextBox,this.EditBox\u粘贴)代码>和
private void EditBox_Paste(object sender, DataObjectPastingEventArgs e)
{
e.CancelCommand();
}
但是,您可能希望允许粘贴,除非它打破了MaxLength,在这种情况下,您需要检查插入的文本及其替换的文本。此时,我决定不在控件中实现MaxLength,而是在表单中处理其余的验证。如果您有单独的问题,则需要将其作为单独的问题发布。@DanPuzey此答案只解决了一半问题。他的问题是它仍然不能阻止粘贴。所以这不是一个单独的问题。