通过编码表示形式限制 TextBox 中 Text 的长度

Constraint length of Text in TextBox by its encoded representation

我有一个TextBox in WPF. I want to restrict the length of the text in the TextBox. There is an easy way to restrict the number of characters by the property MaxLength

在我的用例中,我需要限制文本而不是字符数,而是给定编码中文本的二进制表示的长度。由于程序是德国人使用的,所以有一些变音符号,占用两个字节。

我已经有一个方法可以检查给定的字符串是否适合给定的长度:

public bool IsInLength(string text, int maxLength, Encoding encoding)
{
    return encoding.GetByteCount(text) < maxLength;
}

有没有人知道如何以某种方式将此功能绑定到文本框,使用户不可能输入太多字符以超过最大字节长度。

没有 EventHandler 的解决方案是首选,因为 TextBox 在 DataTemplate.

A​​ 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 个字节的限制)。

我已经扩展了 Alex Klaus 的解决方案以防止输入太长的文本。

public class TextBoxMaxLengthBehavior : Behavior<TextBox>
{
    public static readonly DependencyProperty MaxLengthProperty =
        DependencyProperty.Register(
            nameof(MaxLength),
            typeof(int),
            typeof(TextBoxMaxLengthBehavior),
            new FrameworkPropertyMetadata(0));

    public int MaxLength
    {
        get { return (int) GetValue(MaxLengthProperty); }
        set { SetValue(MaxLengthProperty, value); }
    }

    public static readonly DependencyProperty LengthEncodingProperty =
        DependencyProperty.Register(
            nameof(LengthEncoding),
            typeof(Encoding),
            typeof(TextBoxMaxLengthBehavior),
            new FrameworkPropertyMetadata(Encoding.Default));

    public Encoding LengthEncoding
    {
        get { return (Encoding) GetValue(LengthEncodingProperty); }
        set { SetValue(LengthEncodingProperty, value); }
    }

    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.PreviewTextInput += PreviewTextInputHandler;
        DataObject.AddPastingHandler(AssociatedObject, PastingHandler);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.PreviewTextInput -= PreviewTextInputHandler;
        DataObject.RemovePastingHandler(AssociatedObject, PastingHandler);
    }

    private void PreviewTextInputHandler(object sender, TextCompositionEventArgs e)
    {
        string text;
        if (AssociatedObject.Text.Length < AssociatedObject.CaretIndex)
            text = AssociatedObject.Text;
        else
        {
            //  Remaining text after removing selected text.
            string remainingTextAfterRemoveSelection;

            text = TreatSelectedText(out remainingTextAfterRemoveSelection)
                ? remainingTextAfterRemoveSelection.Insert(AssociatedObject.SelectionStart, e.Text)
                : AssociatedObject.Text.Insert(AssociatedObject.CaretIndex, e.Text);
        }

        e.Handled = !ValidateText(text);
    }

    private bool TreatSelectedText(out string text)
    {
        text = null;
        if (AssociatedObject.SelectionLength <= 0)
            return false;

        var length = AssociatedObject.Text.Length;
        if (AssociatedObject.SelectionStart >= length)
            return true;

        if (AssociatedObject.SelectionStart + AssociatedObject.SelectionLength >= length)
            AssociatedObject.SelectionLength = length - AssociatedObject.SelectionStart;

        text = AssociatedObject.Text.Remove(AssociatedObject.SelectionStart, AssociatedObject.SelectionLength);
        return true;
    }

    private void PastingHandler(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(DataFormats.Text))
        {
            var pastedText = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
            var text = ModifyTextToFit(pastedText);

            if (!ValidateText(text))
                e.CancelCommand();
            else if (text != pastedText)
                e.DataObject.SetData(DataFormats.Text, text);

        }
        else
            e.CancelCommand();
    }

    private string ModifyTextToFit(string text)
    {
        var result = text.Remove(MaxLength);
        while (!string.IsNullOrEmpty(result) && !ValidateText(result))
            result = result.Remove(result.Length - 1);

        return result;
    }

    private bool ValidateText(string text)
    {
        return LengthEncoding.GetByteCount(text) <= MaxLength;
    }
}

在XAML中我可以这样使用它:

<DataTemplate DataType="{x:Type vm:StringViewModel}">
    <TextBox Text="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}">
        <i:Interaction.Behaviors>
            <b:TextBoxMaxLengthBehavior MaxLength="{Binding MaxLength}" LengthEncoding="{Binding LengthEncoding}" />
        </i:Interaction.Behaviors>
    </TextBox>
</DataTemplate>

其中 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"。我希望这会对其他人有所帮助。