我有一个 TextBox
在 WPF 中。我想限制 TextBox
中文本的长度。有一种简单的方法可以通过属性 MaxLength
来限制字符数。 .
在我的用例中,我需要限制文本的不是字符数,而是给定编码中文本的二进制表示的长度。由于程序是德国人使用的,所以有一些元音变音,占用两个字节。
我已经有一个方法可以检查给定的字符串是否适合给定的长度:
public bool IsInLength(string text, int maxLength, Encoding encoding)
{
return encoding.GetByteCount(text) < maxLength;
}
有没有人知道如何以某种方式将此功能绑定(bind)到文本框,使用户不可能输入太多字符以超过最大字节长度。
没有 EventHandler 的解决方案是首选,因为 TextBox 在 DataTemplate 中.
最佳答案
ValidationRule
可能适合这里的要求。这是一个示例实现:
public sealed class ByteCountValidationRule : ValidationRule
{
// For this example I test using an emoji (😄) which will take 2 bytes and fail this rule.
static readonly int MaxByteCount = 1;
static readonly ValidationResult ByteCountExceededResult = new ValidationResult(false, $"Byte count exceeds the maximum allowed limit of {MaxByteCount}");
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var val = value as string;
return val != null && Encoding.UTF8.GetByteCount(val) > MaxByteCount
? ByteCountExceededResult
: ValidationResult.ValidResult;
}
}
XAML 使用:
<TextBox.Text>
<Binding Path="Text" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:ByteCountValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
现在您可以输入 1 个表情符号或 2 个 ascii 字符来触发失败(因为任何一个都会超过 1 个字节的限制)。
关于c# - 通过编码表示形式限制 TextBox 中 Text 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45433516/