【发布时间】:2013-12-20 09:42:03
【问题描述】:
对于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();
}
}
【问题讨论】:
-
TextBox 的内部缓冲区采用 16 位代码单元,因此就 TextBox 而言,“ascii”字符仍占用 2 个字节,因此即使您可以告诉 TextBox 改为计算字节数这不会做你想要的。您必须编写代码来查看 TextBox 拥有的数据并计算数据库将使用多少字节来存储该数据。另外,您确定数据库对所有字符只使用一两个字节吗?如果数据库将数据存储为 UTF-8,则 Unicode 字符可以是一个、两个、三个或四个字节。
标签: c# sql unicode windows-runtime winrt-xaml