如何在winrt中按字节限制文本框maxlength?

时间:2013-12-04 03:35:00

标签: c# sql unicode windows-runtime winrt-xaml

对于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();
    }
}

3 个答案:

答案 0 :(得分:0)

ascii代码也是十六进制的,这意味着一个字符代表2个字节的信息

EX:“A”为41(Hx)0100 0001,为2字节,依此类推

答案 1 :(得分:0)

我认为你应该参考this answer

它建议自己处理这个问题(在这种情况下,它限制了12个字节的长度):

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var textBytes = Encoding.UTF8.GetBytes(textBox1.Text);
    var textByteCount = Encoding.UTF8.GetByteCount(textBox1.Text);
    var textCharCount = Encoding.UTF8.GetCharCount(textBytes);

    if (textCharCount != textByteCount && textByteCount >= 12)
    {
        textBox1.Text = Encoding.UTF32.GetString(Encoding.UTF32.GetBytes(textBox1.Text), 0, 12);
    }
    else if (textBox1.Text.Length >= 6)
    {
        textBox1.Text = textBox1.Text.Substring(0, 6);
    }
}  

答案 2 :(得分:0)

我只使用MaxLengthn的一半varchar(n)