I'm trying to handle the MaxLength of a TextBox via Binding. I'm using a Helper Class called 'MaxLengthConverter' (see here http://mariabrinas.com/?p=89). The TextBox looks currently like this:
<TextBox MaxLength="{Binding TestValue, Mode=TwoWay, Converter={StaticResource MaxLengthConverter}, ConverterParameter='7'}" Text="{Binding TestValue, Mode=TwoWay}" InputScope="Number" />
And the MaxLengthValueConvert looks like this:
public class MaxLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
if (value.ToString().Contains('.'))
{
string[] len = value.ToString().Split('.');
parameter = len[0].Length + 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
The parameter is the length of the value. In this example it's 7. The max. length of the TextBox will be 7, but if the user types a '.' (decimal point), the maxlength will be the current length + 2, so he can only write 23.45 and not 23.456. The problem is that the ValueConvert will only be called when I'm leaving the TextBox (LostFocus). How can I call the ValueConverter every time the user types something in (KeyDown) ?