对于TextBox,有一个属性“MaxLength”,但它把所有ascii和unicode都算作1个字符。
但是在数据库中,我们设置了字段 varchar(n) 。它处理ascii 1和unicode 2。
如何限制按字节输入的文本框?
因为在文本更改之前没有通知,所以解决方法是这样的。
public class TextBoxEx : TextBox
{
private bool bIsChanging;
public TextBoxEx()
{
TextChanged += TextBoxEx_TextChanged;
}
public int MaxByteLength { private get; set; }
private void TextBoxEx_TextChanged(object sender, TextChangedEventArgs e)
{
if (bIsChanging || MaxByteLength == 0 || Text.Length*2 <= MaxByteLength)
return;
bIsChanging = true;
int start = SelectionStart;
Text = TruncateString(Text, MaxByteLength);
SetLimit();
SelectionStart = start;
bIsChanging = false;
}
private void SetLimit()
{
MaxLength = MaxByteLength - Encoding.UTF8.GetBytes(Text).Length + Text.Length;
}
private static string TruncateString(string text, int max)
{
if (max == 0) return text;
byte[] bytes = Encoding.UTF8.GetBytes(text);
if (bytes.Length <= max) return text;
char[] c = text.ToCharArray();
var sb = new StringBuilder();
int count = 0;
foreach (char t in c)
{
count += Encoding.UTF8.GetByteCount(t.ToString());
if (max >= count)
{
sb.Append(t);
}
else
{
break;
}
}
return sb.ToString();
}
}
最佳答案
ascii码也是十六进制的,也就是说一个字符代表2个字节的信息
例如:“A”是 41(Hx) 0100 0001 也就是 2 个字节等等
关于c# - 如何在 winrt 中按字节限制文本框最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366297/