Constraint length of Text in TextBox by its encoded representation

Viewed 1250

I have a 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.

In my use case I need to restrict the text not by the number of characters but by length of the binary representation of the text in a given encoding. As the program is used by germans there are some umlaut, that consume two byte.

I already have a method, that checks, if a given string fits into the given length:

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

Does anybody has an idea how to tie this function to the textbox in a way, that the user has no possibility to enter too much characters to exceed the maximum byte length.

Solutions without EventHandler are prefered as the TextBox is inside a DataTemplate.

2 Answers
Related